body.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package rest
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io"
  6. "net/http"
  7. )
  8. // ReadRequestJSON reads the body of an HTTP request into a target reference.
  9. func ReadRequestJSON(req *http.Request, v any) error {
  10. data, err := io.ReadAll(req.Body)
  11. if err != nil {
  12. return err
  13. }
  14. return json.Unmarshal(data, v)
  15. }
  16. // WriteError writes an error to an HTTP response.
  17. // If the error is a REST API error, it is written as standard per Error.Write.
  18. // Otherwise, ErrInternalServerError is written with the given error attached as data.
  19. func WriteError(w http.ResponseWriter, err error) error {
  20. if errors.Is(err, Err) {
  21. _, ret := err.(Error).Write(w)
  22. return ret
  23. }
  24. _, ret := ErrInternalServerError.WithError(err).Write(w)
  25. return ret
  26. }
  27. // WriteErrorJSON writes an error as JSON to an HTTP response.
  28. // If the error is a REST API error, it is written as standard per Error.WriteJSON.
  29. // Otherwise, ErrInternalServerError is written with the given error attached as data.
  30. func WriteErrorJSON(w http.ResponseWriter, err error) error {
  31. if errors.Is(err, Err) {
  32. return err.(Error).WriteJSON(w)
  33. }
  34. return ErrInternalServerError.WithError(err).WriteJSON(w)
  35. }
  36. // WriteResponseJSON writes an HTTP response as JSON.
  37. func WriteResponseJSON(w http.ResponseWriter, statusCode int, data any) error {
  38. b, err := json.Marshal(data)
  39. if err != nil {
  40. return err
  41. }
  42. w.Header().Add("Content-Type", "application/json")
  43. w.WriteHeader(statusCode)
  44. w.Write(b)
  45. return nil
  46. }