read.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Package read implements request object readers.
  2. package read
  3. import (
  4. "bytes"
  5. "encoding/json"
  6. "fmt"
  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/authority/admin"
  12. "github.com/smallstep/certificates/internal/buffer"
  13. )
  14. // JSON unmarshals from the given request's JSON body into v. In case of an
  15. // error a HTTP Bad Request error will be written to w.
  16. func JSON(w http.ResponseWriter, r *http.Request, v interface{}) bool {
  17. b := read(w, r)
  18. if b == nil {
  19. return false
  20. }
  21. defer buffer.Put(b)
  22. if err := json.NewDecoder(b).Decode(v); err != nil {
  23. err = fmt.Errorf("error decoding json: %w", err)
  24. render.BadRequest(w, err)
  25. return false
  26. }
  27. return true
  28. }
  29. // AdminJSON is obsolete; it's here for backwards compatibility.
  30. //
  31. // Please don't use.
  32. func AdminJSON(w http.ResponseWriter, r *http.Request, v interface{}) bool {
  33. b := read(w, r)
  34. if b == nil {
  35. return false
  36. }
  37. defer buffer.Put(b)
  38. if err := json.NewDecoder(b).Decode(v); err != nil {
  39. e := admin.WrapError(admin.ErrorBadRequestType, err, "error reading request body")
  40. admin.WriteError(w, e)
  41. return false
  42. }
  43. return true
  44. }
  45. // ProtoJSON reads JSON from the request body and stores it in the value
  46. // pointed by v.
  47. func ProtoJSON(w http.ResponseWriter, r *http.Request, m proto.Message) bool {
  48. b := read(w, r)
  49. if b == nil {
  50. return false
  51. }
  52. defer buffer.Put(b)
  53. if err := protojson.Unmarshal(b.Bytes(), m); err != nil {
  54. err = fmt.Errorf("error decoding proto json: %w", err)
  55. render.BadRequest(w, err)
  56. return false
  57. }
  58. return true
  59. }
  60. func read(w http.ResponseWriter, r *http.Request) *bytes.Buffer {
  61. b := buffer.Get()
  62. if _, err := b.ReadFrom(r.Body); err != nil {
  63. buffer.Put(b)
  64. err = fmt.Errorf("error reading request body: %w", err)
  65. render.BadRequest(w, err)
  66. return nil
  67. }
  68. return b
  69. }