read.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 to 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. switch err := protojson.Unmarshal(data, m); {
  29. case errors.Is(err, proto.Error):
  30. return badProtoJSONError(err.Error())
  31. default:
  32. return err
  33. }
  34. }
  35. // badProtoJSONError is an error type that is returned by ProtoJSON
  36. // when a proto message cannot be unmarshaled. Usually this is caused
  37. // by an error in the request body.
  38. type badProtoJSONError string
  39. // Error implements error for badProtoJSONError
  40. func (e badProtoJSONError) Error() string {
  41. return string(e)
  42. }
  43. // Render implements render.RenderableError for badProtoJSONError
  44. func (e badProtoJSONError) Render(w http.ResponseWriter) {
  45. v := struct {
  46. Type string `json:"type"`
  47. Detail string `json:"detail"`
  48. Message string `json:"message"`
  49. }{
  50. Type: "badRequest",
  51. Detail: "bad request",
  52. Message: e.Error(),
  53. }
  54. render.JSONStatus(w, v, http.StatusBadRequest)
  55. }