fusen-gateway/server/logic/gateway_response.go
2023-11-07 11:16:29 +08:00

54 lines
1.1 KiB
Go

package logic
import (
"bytes"
"context"
"fusen-basic/basic"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
type EmptyMarshaler struct {
runtime.JSONPb
}
func (m *EmptyMarshaler) Marshal(v interface{}) ([]byte, error) {
return nil, nil
}
var fsProtoJSON = &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
EmitUnpopulated: true,
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
}
func ResponseHeaderMatcher(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
headers := w.Header()
key := http.CanonicalHeaderKey("Grpc-Metadata-" + string(basic.GM_FusenResponse))
if location, ok := headers[key]; ok {
// w.Header().Set("Location", location[0])
// w.WriteHeader(http.StatusFound)
w.WriteHeader(200)
fsHeader := location[0]
var buf = bytes.NewBufferString(fsHeader[:len(fsHeader)-1] + ",")
rdata, err := fsProtoJSON.Marshal(resp)
if err != nil {
return err
}
buf.WriteString(`"data":`)
buf.Write(rdata)
buf.WriteString(`}`)
w.Write(buf.Bytes())
}
return nil
}