fusen-gateway/server/logic/gateway_response.go

101 lines
2.3 KiB
Go
Raw Permalink 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-15 06:32:14 +00:00
"fmt"
2023-11-07 03:16:29 +00:00
"fusen-basic/basic"
"fusen-gateway/gen/go/service"
2023-11-02 10:40:22 +00:00
"net/http"
2023-11-15 06:32:14 +00:00
"regexp"
2023-11-02 10:40:22 +00:00
"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 fsDefaultProtoJSON = &runtime.JSONPb{
MarshalOptions: protojson.MarshalOptions{
EmitUnpopulated: true,
2023-11-17 10:35:28 +00:00
UseProtoNames: true,
2023-11-02 10:40:22 +00:00
},
UnmarshalOptions: protojson.UnmarshalOptions{
DiscardUnknown: true,
},
}
2023-11-15 06:32:14 +00:00
var codeRE = regexp.MustCompile(`(?i)"code"\s*:\s*(\d+)`)
func WriteFusenResponse(fsHeader string, w http.ResponseWriter, resp proto.Message) error {
w.WriteHeader(200)
var buf = bytes.NewBufferString(fsHeader[:len(fsHeader)-1] + ",")
var rdata []byte
var err error
if customResp, ok := resp.(*service.Response); ok {
2023-11-17 10:35:28 +00:00
if customResp.GetData() != nil {
rdata, err = fsDefaultProtoJSON.Marshal(customResp.GetData())
if err != nil {
return err
}
} else {
rdata = []byte("null")
}
} else {
2023-11-17 10:35:28 +00:00
rdata, err = fsDefaultProtoJSON.Marshal(resp)
if err != nil {
return err
}
2023-11-15 06:32:14 +00:00
}
2023-11-15 06:32:14 +00:00
buf.WriteString(`"data":`)
buf.Write(rdata)
buf.WriteString(`}`)
w.Write(buf.Bytes())
return nil
}
2023-11-02 10:40:22 +00:00
func ResponseHeaderMatcher(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
headers := w.Header()
2023-11-14 09:33:19 +00:00
key := http.CanonicalHeaderKey(basic.GM_FusenResponse.GrpcMetadataKey())
2023-11-15 06:32:14 +00:00
2023-11-14 09:33:19 +00:00
if grpcResp, ok := headers[key]; ok {
2023-11-15 06:32:14 +00:00
fsHeader := grpcResp[0]
code := codeRE.FindStringSubmatch(string(fsHeader))
if len(code) > 0 && code[1] != "200" {
return WriteFusenResponse(fsHeader, w, resp)
}
2023-11-14 09:33:19 +00:00
// 判断自定返回的内容, 用html的页面返回等...
selfwrite := http.CanonicalHeaderKey(basic.GM_SelfWrite.GrpcMetadataKey())
if sw, ok := headers[selfwrite]; ok {
w.WriteHeader(200)
w.Write([]byte(sw[0]))
return nil
}
// 重定向
redirect := http.CanonicalHeaderKey(basic.GM_Redirect.GrpcMetadataKey())
if location, ok := headers[redirect]; ok {
w.WriteHeader(http.StatusFound)
w.Header().Set("Location", location[0])
return nil
}
2023-11-15 06:32:14 +00:00
return WriteFusenResponse(fsHeader, w, resp)
2023-11-02 10:40:22 +00:00
}
2023-11-03 03:06:15 +00:00
2023-11-15 06:32:14 +00:00
w.Write([]byte(fmt.Sprintf("%s error", basic.GM_FusenResponse.String())))
2023-11-02 10:40:22 +00:00
return nil
}