Core functionality for new aiterp.net servers
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
1.9 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. package wrouter
  2. import (
  3. "net/http"
  4. "strings"
  5. "git.aiterp.net/gisle/wrouter/response"
  6. "git.aiterp.net/gisle/wrouter/auth"
  7. )
  8. type Func func(http.ResponseWriter, *http.Request, *auth.User)
  9. type IDFunc func(http.ResponseWriter, *http.Request, string, *auth.User)
  10. type Resource struct {
  11. list Func
  12. create Func
  13. get IDFunc
  14. update IDFunc
  15. delete IDFunc
  16. PrivateRead bool
  17. PrivateWrite bool
  18. }
  19. func NewResource(list, create Func, get, update, delete IDFunc) *Resource {
  20. return &Resource{list, create, get, update, delete, false, false}
  21. }
  22. func (resource *Resource) Handle(path string, w http.ResponseWriter, req *http.Request, user *auth.User) bool {
  23. // Get the subpath out of the path
  24. subpath := req.URL.Path[len(path):]
  25. if len(subpath) > 0 && subpath[0] == '/' {
  26. subpath = subpath[1:]
  27. }
  28. // Error out on bad IDs which contains /es
  29. if x := strings.Index(subpath, "/"); x != -1 {
  30. response.Text(w, 400, "Invalid ID: "+subpath)
  31. return true
  32. }
  33. // Route it to the resource
  34. switch req.Method {
  35. case "GET":
  36. {
  37. if resource.PrivateRead && user == nil {
  38. response.Text(w, 401, "Not logged in")
  39. return true
  40. }
  41. if subpath != "" {
  42. resource.get(w, req, subpath, user)
  43. } else {
  44. resource.list(w, req, user)
  45. }
  46. }
  47. case "POST":
  48. {
  49. if resource.PrivateWrite && user == nil {
  50. response.Text(w, 401, "Not logged in")
  51. return true
  52. }
  53. if subpath != "" {
  54. response.Text(w, 400, "ID not allowed in POST")
  55. return true
  56. }
  57. resource.create(w, req, user)
  58. }
  59. case "PATCH", "PUT":
  60. {
  61. if resource.PrivateWrite && user == nil {
  62. response.Text(w, 401, "Not logged in")
  63. return true
  64. }
  65. resource.update(w, req, subpath, user)
  66. }
  67. case "DELETE":
  68. {
  69. if resource.PrivateWrite && user == nil {
  70. response.Text(w, 401, "Not logged in")
  71. return true
  72. }
  73. resource.delete(w, req, subpath, user)
  74. }
  75. }
  76. return true
  77. }