read.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Package read implements request object readers.
  2. package read
  3. import (
  4. "encoding/json"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "google.golang.org/protobuf/encoding/protojson"
  10. "google.golang.org/protobuf/proto"
  11. "github.com/smallstep/certificates/api/render"
  12. "github.com/smallstep/certificates/errs"
  13. )
  14. // JSON reads JSON from the request body and stores it in the value
  15. // pointed to by v.
  16. func JSON(r io.Reader, v any) error {
  17. if err := json.NewDecoder(r).Decode(v); err != nil {
  18. return errs.BadRequestErr(err, "error decoding json")
  19. }
  20. return nil
  21. }
  22. // ProtoJSON reads JSON from the request body and stores it in the value
  23. // pointed to by m.
  24. func ProtoJSON(r io.Reader, m proto.Message) error {
  25. data, err := io.ReadAll(r)
  26. if err != nil {
  27. return errs.BadRequestErr(err, "error reading request body")
  28. }
  29. switch err := protojson.Unmarshal(data, m); {
  30. case errors.Is(err, proto.Error):
  31. return badProtoJSONError(err.Error())
  32. default:
  33. return err
  34. }
  35. }
  36. // badProtoJSONError is an error type that is returned by ProtoJSON
  37. // when a proto message cannot be unmarshaled. Usually this is caused
  38. // by an error in the request body.
  39. type badProtoJSONError string
  40. // Error implements error for badProtoJSONError
  41. func (e badProtoJSONError) Error() string {
  42. return string(e)
  43. }
  44. // Render implements render.RenderableError for badProtoJSONError
  45. func (e badProtoJSONError) Render(w http.ResponseWriter, r *http.Request) {
  46. v := struct {
  47. Type string `json:"type"`
  48. Detail string `json:"detail"`
  49. Message string `json:"message"`
  50. }{
  51. Type: "badRequest",
  52. Detail: "bad request",
  53. // trim the proto prefix for the message
  54. Message: strings.TrimSpace(strings.TrimPrefix(e.Error(), "proto:")),
  55. }
  56. render.JSONStatus(w, r, v, http.StatusBadRequest)
  57. }