1
0

body.go 599 B

12345678910111213141516171819202122232425262728
  1. package rest
  2. import (
  3. "encoding/json"
  4. "io"
  5. "net/http"
  6. )
  7. // ReadRequestJSON reads the body of an HTTP request into a target reference.
  8. func ReadRequestJSON(req *http.Request, v any) error {
  9. data, err := io.ReadAll(req.Body)
  10. if err != nil {
  11. return err
  12. }
  13. return json.Unmarshal(data, v)
  14. }
  15. // WriteResponseJSON writes an HTTP response as JSON.
  16. func WriteResponseJSON(w http.ResponseWriter, statusCode int, data any) error {
  17. b, err := json.Marshal(data)
  18. if err != nil {
  19. return err
  20. }
  21. w.Header().Add("Content-Type", "application/json")
  22. w.WriteHeader(statusCode)
  23. w.Write(b)
  24. return nil
  25. }