From 7fb8acda2778c9188e6d19583ce041f4706629fe Mon Sep 17 00:00:00 2001 From: Panagiotis Siatras Date: Fri, 18 Mar 2022 15:21:40 +0200 Subject: [PATCH] api/read: initial implementation of the package --- api/read/read.go | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 api/read/read.go diff --git a/api/read/read.go b/api/read/read.go new file mode 100644 index 00000000..fab8fa8f --- /dev/null +++ b/api/read/read.go @@ -0,0 +1,30 @@ +// Package read implements request object readers. +package read + +import ( + "encoding/json" + "io" + + "github.com/smallstep/certificates/errs" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" +) + +// JSON reads JSON from the request body and stores it in the value +// pointed by v. +func JSON(r io.Reader, v interface{}) error { + if err := json.NewDecoder(r).Decode(v); err != nil { + return errs.BadRequestErr(err, "error decoding json") + } + return nil +} + +// ProtoJSON reads JSON from the request body and stores it in the value +// pointed by v. +func ProtoJSON(r io.Reader, m proto.Message) error { + data, err := io.ReadAll(r) + if err != nil { + return errs.BadRequestErr(err, "error reading request body") + } + return protojson.Unmarshal(data, m) +}