api.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package api
  2. import (
  3. "io"
  4. "net/http"
  5. "github.com/annybs/ezdb"
  6. "github.com/annybs/go/rest"
  7. "github.com/annybs/go/validate"
  8. "github.com/rs/zerolog"
  9. )
  10. type API struct {
  11. DB ezdb.Collection[[]byte]
  12. Log zerolog.Logger
  13. Token string
  14. }
  15. func (api *API) Delete(w http.ResponseWriter, req *http.Request) {
  16. if !rest.IsAuthenticated(req, api.Token) {
  17. w.WriteHeader(http.StatusUnauthorized)
  18. w.Write([]byte{})
  19. return
  20. }
  21. path := req.URL.Path
  22. if exist, _ := api.DB.Has(path); !exist {
  23. w.Write([]byte{})
  24. return
  25. }
  26. if err := api.DB.Delete(path); err != nil {
  27. w.WriteHeader(http.StatusInternalServerError)
  28. w.Write([]byte(err.Error()))
  29. } else {
  30. w.Write([]byte{})
  31. }
  32. }
  33. func (api *API) Get(w http.ResponseWriter, req *http.Request) {
  34. path := req.URL.Path
  35. dest, _ := api.DB.Get(path)
  36. if len(dest) > 0 {
  37. w.Header().Set("Location", string(dest))
  38. w.WriteHeader(http.StatusPermanentRedirect)
  39. } else {
  40. w.WriteHeader(http.StatusNotFound)
  41. }
  42. w.Write([]byte{})
  43. }
  44. func (api *API) Put(w http.ResponseWriter, req *http.Request) {
  45. if !rest.IsAuthenticated(req, api.Token) {
  46. w.WriteHeader(http.StatusUnauthorized)
  47. w.Write([]byte{})
  48. return
  49. }
  50. path := req.URL.Path
  51. dest, err := io.ReadAll(req.Body)
  52. if err != nil {
  53. w.WriteHeader(http.StatusBadRequest)
  54. w.Write([]byte(err.Error()))
  55. return
  56. }
  57. if err := validate.URL(string(dest)); err != nil {
  58. w.WriteHeader(http.StatusBadRequest)
  59. w.Write([]byte(err.Error()))
  60. return
  61. }
  62. if err := api.DB.Put(path, dest); err != nil {
  63. w.WriteHeader(http.StatusInternalServerError)
  64. w.Write([]byte(err.Error()))
  65. } else {
  66. w.Write([]byte{})
  67. }
  68. }
  69. func (api *API) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  70. api.Log.Info().Msgf("%s %s", req.Method, req.URL.Path)
  71. switch req.Method {
  72. case http.MethodGet:
  73. api.Get(w, req)
  74. case http.MethodPut:
  75. api.Put(w, req)
  76. case http.MethodDelete:
  77. api.Delete(w, req)
  78. default:
  79. w.WriteHeader(http.StatusBadRequest)
  80. w.Write([]byte("unsupported method"))
  81. }
  82. }