mirror of
https://github.com/zeromicro/go-zero.git
synced 2025-01-23 09:00:20 +08:00
chore: refactor gateway (#2303)
This commit is contained in:
parent
22bb7e95fd
commit
93584c6ca6
47
gateway/internal/eventhandler.go
Normal file
47
gateway/internal/eventhandler.go
Normal file
@ -0,0 +1,47 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/golang/protobuf/jsonpb"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/jhump/protoreflect/desc"
|
||||
"github.com/zeromicro/go-zero/core/logx"
|
||||
"google.golang.org/grpc/metadata"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
type EventHandler struct {
|
||||
Status *status.Status
|
||||
writer io.Writer
|
||||
marshaler jsonpb.Marshaler
|
||||
}
|
||||
|
||||
func NewEventHandler(writer io.Writer, resolver jsonpb.AnyResolver) *EventHandler {
|
||||
return &EventHandler{
|
||||
writer: writer,
|
||||
marshaler: jsonpb.Marshaler{
|
||||
EmitDefaults: true,
|
||||
AnyResolver: resolver,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (h *EventHandler) OnResolveMethod(_ *desc.MethodDescriptor) {
|
||||
}
|
||||
|
||||
func (h *EventHandler) OnSendHeaders(_ metadata.MD) {
|
||||
}
|
||||
|
||||
func (h *EventHandler) OnReceiveHeaders(_ metadata.MD) {
|
||||
}
|
||||
|
||||
func (h *EventHandler) OnReceiveResponse(message proto.Message) {
|
||||
if err := h.marshaler.Marshal(h.writer, message); err != nil {
|
||||
logx.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *EventHandler) OnReceiveTrailers(status *status.Status, _ metadata.MD) {
|
||||
h.Status = status
|
||||
}
|
@ -120,11 +120,6 @@ func (s *Server) build() error {
|
||||
func (s *Server) buildHandler(source grpcurl.DescriptorSource, resolver jsonpb.AnyResolver,
|
||||
cli zrpc.Client, rpcPath string) func(http.ResponseWriter, *http.Request) {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
handler := &grpcurl.DefaultEventHandler{
|
||||
Out: w,
|
||||
Formatter: grpcurl.NewJSONFormatter(true,
|
||||
grpcurl.AnyResolverFromDescriptorSource(source)),
|
||||
}
|
||||
parser, err := internal.NewRequestParser(r, resolver)
|
||||
if err != nil {
|
||||
httpx.Error(w, err)
|
||||
@ -136,6 +131,7 @@ func (s *Server) buildHandler(source grpcurl.DescriptorSource, resolver jsonpb.A
|
||||
defer can()
|
||||
|
||||
w.Header().Set(httpx.ContentType, httpx.JsonContentType)
|
||||
handler := internal.NewEventHandler(w, resolver)
|
||||
if err := grpcurl.InvokeRPC(ctx, source, cli.Conn(), rpcPath, s.prepareMetadata(r.Header),
|
||||
handler, parser.Next); err != nil {
|
||||
httpx.Error(w, err)
|
||||
|
Loading…
Reference in New Issue
Block a user