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.

72 lines
1.5 KiB

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