read.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Package read implements request object readers.
  2. package read
  3. import (
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "google.golang.org/protobuf/encoding/protojson"
  9. "google.golang.org/protobuf/proto"
  10. "github.com/smallstep/certificates/api/render"
  11. "github.com/smallstep/certificates/errs"
  12. )
  13. // JSON reads JSON from the request body and stores it in the value
  14. // pointed by v.
  15. func JSON(r io.Reader, v interface{}) error {
  16. if err := json.NewDecoder(r).Decode(v); err != nil {
  17. return errs.BadRequestErr(err, "error decoding json")
  18. }
  19. return nil
  20. }
  21. // ProtoJSON reads JSON from the request body and stores it in the value
  22. // pointed by v.
  23. func ProtoJSON(r io.Reader, m proto.Message) error {
  24. data, err := io.ReadAll(r)
  25. if err != nil {
  26. return errs.BadRequestErr(err, "error reading request body")
  27. }
  28. return protojson.Unmarshal(data, m)
  29. }
  30. // ProtoJSONWithCheck reads JSON from the request body and stores it in the value
  31. // pointed to by v. Returns false if an error was written; true if not.
  32. func ProtoJSONWithCheck(w http.ResponseWriter, r io.Reader, m proto.Message) bool {
  33. data, err := io.ReadAll(r)
  34. if err != nil {
  35. var wrapper = struct {
  36. Status int `json:"code"`
  37. Message string `json:"message"`
  38. }{
  39. Status: http.StatusBadRequest,
  40. Message: err.Error(),
  41. }
  42. errData, err := json.Marshal(wrapper)
  43. if err != nil {
  44. panic(err)
  45. }
  46. w.Header().Set("Content-Type", "application/json")
  47. w.WriteHeader(http.StatusBadRequest)
  48. w.Write(errData)
  49. return false
  50. }
  51. if err := protojson.Unmarshal(data, m); err != nil {
  52. if errors.Is(err, proto.Error) {
  53. var wrapper = struct {
  54. Message string `json:"message"`
  55. }{
  56. Message: err.Error(),
  57. }
  58. errData, err := json.Marshal(wrapper)
  59. if err != nil {
  60. panic(err)
  61. }
  62. w.Header().Set("Content-Type", "application/json")
  63. w.WriteHeader(http.StatusBadRequest)
  64. w.Write(errData)
  65. return false
  66. }
  67. // fallback to the default error writer
  68. render.Error(w, err)
  69. return false
  70. }
  71. return true
  72. }