package encoders import ( "github.com/pkg/errors" pb "go.unistack.org/unistack-org/pkgdash/proto" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" "io" "net/http" ) var ErrWrongResponseType = errors.New("JSONProto: wrong response message type") type JSONProto struct { m protojson.MarshalOptions } func NewJSONProto() *JSONProto { return &JSONProto{m: protojson.MarshalOptions{ EmitUnpopulated: true, UseProtoNames: false, }} } func (e *JSONProto) Success(rw http.ResponseWriter, response interface{}) error { rw.Header().Set("Content-Type", "application/json; charset=utf-8") rw.WriteHeader(http.StatusOK) if v, ok := response.(proto.Message); ok { return errors.WithStack(e.Fmarshal(rw, v)) } return ErrWrongResponseType } func (e *JSONProto) Error(rw http.ResponseWriter, err *pb.Error, status int) error { rw.Header().Set("Content-Type", "application/problem+json; charset=utf-8") rw.WriteHeader(status) return errors.WithStack(e.Fmarshal(rw, &pb.ErrorRsp{Error: err})) } func (e *JSONProto) Fmarshal(w io.Writer, m proto.Message) error { b, err := e.m.Marshal(m) if len(b) > 0 { if _, err = w.Write(b); err != nil { return err } } return err }