add storage and mux handle with handlers
This commit is contained in:
25
handler/encoders/json.go
Normal file
25
handler/encoders/json.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package encoders
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
pb "go.unistack.org/unistack-org/pkgdash/proto/go_generate"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type JSON struct{}
|
||||
|
||||
func (*JSON) Success(rw http.ResponseWriter, response interface{}) error {
|
||||
rw.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
rw.WriteHeader(http.StatusOK)
|
||||
|
||||
return errors.WithStack(json.NewEncoder(rw).Encode(response))
|
||||
}
|
||||
|
||||
func (*JSON) 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(json.NewEncoder(rw).Encode(&pb.ErrorRsp{Error: err}))
|
||||
}
|
51
handler/encoders/jsonpb.go
Normal file
51
handler/encoders/jsonpb.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package encoders
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
pb "go.unistack.org/unistack-org/pkgdash/proto/go_generate"
|
||||
"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
|
||||
}
|
Reference in New Issue
Block a user