fusen-gateway/server/logic/gateway_response.go
2023-11-02 18:40:22 +08:00

57 lines
1.2 KiB
Go

package logic
import (
"context"
"encoding/json"
"fusen-gateway/proto/goutils/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.M_FusenResponse))
w.WriteHeader(200)
if location, ok := headers[key]; ok {
// w.Header().Set("Location", location[0])
// w.WriteHeader(http.StatusFound)
jbuf := []byte(location[0])
gresp := &basic.GatewayResponse{}
err := json.Unmarshal(jbuf, gresp)
if err != nil {
return err
}
gresp.Data = resp
rdata, err := fsProtoJSON.Marshal(resp)
if err != nil {
return err
}
w.Write(rdata)
}
// w.WriteHeader(200)
// w.Write([]byte("error"))
return nil
}