read.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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/errs"
  11. )
  12. // JSON reads JSON from the request body and stores it in the value
  13. // pointed by v.
  14. func JSON(r io.Reader, v interface{}) error {
  15. if err := json.NewDecoder(r).Decode(v); err != nil {
  16. return errs.BadRequestErr(err, "error decoding json")
  17. }
  18. return nil
  19. }
  20. // ProtoJSON reads JSON from the request body and stores it in the value
  21. // pointed to by v.
  22. func ProtoJSON(r io.Reader, m proto.Message) error {
  23. data, err := io.ReadAll(r)
  24. if err != nil {
  25. return errs.BadRequestErr(err, "error reading request body")
  26. }
  27. if err := protojson.Unmarshal(data, m); err != nil {
  28. if errors.Is(err, proto.Error) {
  29. return newBadProtoJSONError(err)
  30. }
  31. }
  32. return err
  33. }
  34. // BadProtoJSONError is an error type that is used when a proto
  35. // message cannot be unmarshaled. Usually this is caused by an error
  36. // in the request body.
  37. type BadProtoJSONError struct {
  38. err error
  39. Type string `json:"type"`
  40. Detail string `json:"detail"`
  41. Message string `json:"message"`
  42. }
  43. // newBadProtoJSONError returns a new instance of BadProtoJSONError
  44. // This error type is always caused by an error in the request body.
  45. func newBadProtoJSONError(err error) *BadProtoJSONError {
  46. return &BadProtoJSONError{
  47. err: err,
  48. Type: "badRequest",
  49. Detail: "bad request",
  50. Message: err.Error(),
  51. }
  52. }
  53. // Error implements the error interface
  54. func (e *BadProtoJSONError) Error() string {
  55. return e.err.Error()
  56. }
  57. // Render implements render.RenderableError for BadProtoError
  58. func (e *BadProtoJSONError) Render(w http.ResponseWriter) {
  59. errData, err := json.Marshal(e)
  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. }