fusen-gateway/server/logic/gateway_response.go

54 lines
1.1 KiB
Go
Raw Normal View History

2023-11-02 10:40:22 +00:00
package logic
import (
2023-11-03 03:06:15 +00:00
"bytes"
2023-11-02 10:40:22 +00:00
"context"
2023-11-07 03:16:29 +00:00
"fusen-basic/basic"
2023-11-02 10:40:22 +00:00
"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()
2023-11-03 03:06:15 +00:00
key := http.CanonicalHeaderKey("Grpc-Metadata-" + string(basic.GM_FusenResponse))
2023-11-02 10:40:22 +00:00
if location, ok := headers[key]; ok {
// w.Header().Set("Location", location[0])
// w.WriteHeader(http.StatusFound)
2023-11-03 03:06:15 +00:00
w.WriteHeader(200)
fsHeader := location[0]
var buf = bytes.NewBufferString(fsHeader[:len(fsHeader)-1] + ",")
2023-11-02 10:40:22 +00:00
rdata, err := fsProtoJSON.Marshal(resp)
if err != nil {
return err
}
2023-11-03 03:06:15 +00:00
buf.WriteString(`"data":`)
buf.Write(rdata)
buf.WriteString(`}`)
2023-11-02 10:40:22 +00:00
2023-11-03 03:06:15 +00:00
w.Write(buf.Bytes())
2023-11-02 10:40:22 +00:00
}
2023-11-03 03:06:15 +00:00
2023-11-02 10:40:22 +00:00
return nil
}