read.go 781 B

12345678910111213141516171819202122232425262728293031
  1. // Package read implements request object readers.
  2. package read
  3. import (
  4. "encoding/json"
  5. "io"
  6. "google.golang.org/protobuf/encoding/protojson"
  7. "google.golang.org/protobuf/proto"
  8. "github.com/smallstep/certificates/errs"
  9. )
  10. // JSON reads JSON from the request body and stores it in the value
  11. // pointed by v.
  12. func JSON(r io.Reader, v interface{}) error {
  13. if err := json.NewDecoder(r).Decode(v); err != nil {
  14. return errs.BadRequestErr(err, "error decoding json")
  15. }
  16. return nil
  17. }
  18. // ProtoJSON reads JSON from the request body and stores it in the value
  19. // pointed by v.
  20. func ProtoJSON(r io.Reader, m proto.Message) error {
  21. data, err := io.ReadAll(r)
  22. if err != nil {
  23. return errs.BadRequestErr(err, "error reading request body")
  24. }
  25. return protojson.Unmarshal(data, m)
  26. }