2023-08-09 14:31:23 +03:00
|
|
|
package encoders
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/pkg/errors"
|
2023-08-11 21:27:38 +03:00
|
|
|
pb "go.unistack.org/unistack-org/pkgdash/proto"
|
2023-08-09 14:31:23 +03:00
|
|
|
"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
|
|
|
|
}
|