更新网关

This commit is contained in:
eson
2023-11-15 14:32:14 +08:00
parent b20cb4b7c3
commit 309b18a2b7
4 changed files with 42 additions and 19 deletions

View File

@@ -0,0 +1,12 @@
package logic
import (
"log"
"testing"
)
func TestRe(t *testing.T) {
fsHeader := `{"code": 200 , "msg":"asd"}`
code := codeRE.FindStringSubmatch(string(fsHeader))
log.Println(code)
}

View File

@@ -3,8 +3,10 @@ package logic
import (
"bytes"
"context"
"fmt"
"fusen-basic/basic"
"net/http"
"regexp"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"google.golang.org/protobuf/encoding/protojson"
@@ -28,13 +30,34 @@ var fsProtoJSON = &runtime.JSONPb{
},
}
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] + ",")
rdata, err := fsProtoJSON.Marshal(resp)
if err != nil {
return err
}
buf.WriteString(`"data":`)
buf.Write(rdata)
buf.WriteString(`}`)
w.Write(buf.Bytes())
return nil
}
func ResponseHeaderMatcher(ctx context.Context, w http.ResponseWriter, resp proto.Message) error {
headers := w.Header()
key := http.CanonicalHeaderKey(basic.GM_FusenResponse.GrpcMetadataKey())
if grpcResp, ok := headers[key]; ok {
// w.Header().Set("Location", location[0])
// w.WriteHeader(http.StatusFound)
fsHeader := grpcResp[0]
code := codeRE.FindStringSubmatch(string(fsHeader))
if len(code) > 0 && code[1] != "200" {
return WriteFusenResponse(fsHeader, w, resp)
}
// 判断自定返回的内容, 用html的页面返回等...
selfwrite := http.CanonicalHeaderKey(basic.GM_SelfWrite.GrpcMetadataKey())
@@ -52,21 +75,9 @@ func ResponseHeaderMatcher(ctx context.Context, w http.ResponseWriter, resp prot
return nil
}
w.WriteHeader(200)
fsHeader := grpcResp[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
return WriteFusenResponse(fsHeader, w, resp)
}
w.Write([]byte("GM_FusenResponse error"))
w.Write([]byte(fmt.Sprintf("%s error", basic.GM_FusenResponse.String())))
return nil
}