read.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. // TODO(hs): refactor this after the API flow changes are in (or before if that works)
  33. func ProtoJSONWithCheck(w http.ResponseWriter, r io.Reader, m proto.Message) bool {
  34. data, err := io.ReadAll(r)
  35. if err != nil {
  36. var wrapper = struct {
  37. Status int `json:"code"`
  38. Message string `json:"message"`
  39. }{
  40. Status: http.StatusBadRequest,
  41. Message: err.Error(),
  42. }
  43. errData, err := json.Marshal(wrapper)
  44. if err != nil {
  45. panic(err)
  46. }
  47. w.Header().Set("Content-Type", "application/json")
  48. w.WriteHeader(http.StatusBadRequest)
  49. w.Write(errData)
  50. return false
  51. }
  52. if err := protojson.Unmarshal(data, m); err != nil {
  53. if errors.Is(err, proto.Error) {
  54. var wrapper = struct {
  55. Type string `json:"type"`
  56. Detail string `json:"detail"`
  57. Message string `json:"message"`
  58. }{
  59. Type: "badRequest",
  60. Detail: "bad request",
  61. Message: err.Error(),
  62. }
  63. errData, err := json.Marshal(wrapper)
  64. if err != nil {
  65. panic(err)
  66. }
  67. w.Header().Set("Content-Type", "application/json")
  68. w.WriteHeader(http.StatusBadRequest)
  69. w.Write(errData)
  70. return false
  71. }
  72. // fallback to the default error writer
  73. render.Error(w, err)
  74. return false
  75. }
  76. return true
  77. }