4
0

read.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 m. 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. // TODO(hs): more properties in the error response?
  55. Message string `json:"message"`
  56. }{
  57. Message: err.Error(),
  58. }
  59. errData, err := json.Marshal(wrapper)
  60. if err != nil {
  61. panic(err)
  62. }
  63. w.Header().Set("Content-Type", "application/json")
  64. w.WriteHeader(http.StatusBadRequest)
  65. w.Write(errData)
  66. return false
  67. }
  68. // fallback to the default error writer
  69. render.Error(w, err)
  70. return false
  71. }
  72. return true
  73. }