documents.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package documents
  2. import (
  3. "bytes"
  4. "excalidraw-complete/core"
  5. "io"
  6. "net/http"
  7. "github.com/go-chi/chi/v5"
  8. "github.com/go-chi/render"
  9. )
  10. type (
  11. DocumentCreateResponse struct {
  12. ID string `json:"id"`
  13. }
  14. )
  15. func HandleCreate(documentStore core.DocumentStore) http.HandlerFunc {
  16. return func(w http.ResponseWriter, r *http.Request) {
  17. data := new(bytes.Buffer)
  18. _, err := io.Copy(data, r.Body)
  19. if err != nil {
  20. http.Error(w, "Failed to copy", http.StatusInternalServerError)
  21. return
  22. }
  23. id, err := documentStore.Create(r.Context(), &core.Document{Data: *data})
  24. if err != nil {
  25. http.Error(w, "Failed to save", http.StatusInternalServerError)
  26. return
  27. }
  28. render.JSON(w, r, DocumentCreateResponse{ID: id})
  29. render.Status(r, http.StatusOK)
  30. }
  31. }
  32. func HandleGet(documentStore core.DocumentStore) http.HandlerFunc {
  33. return func(w http.ResponseWriter, r *http.Request) {
  34. id := chi.URLParam(r, "id")
  35. document, err := documentStore.FindID(r.Context(), id)
  36. if err != nil {
  37. http.Error(w, "not found", http.StatusNotFound)
  38. return
  39. }
  40. w.Write(document.Data.Bytes())
  41. }
  42. }