Skip to content

Commit

Permalink
feat:add x-http-code response header
Browse files Browse the repository at this point in the history
  • Loading branch information
geebytes committed May 20, 2024
1 parent aeab21e commit 9f2bb43
Show file tree
Hide file tree
Showing 15 changed files with 122 additions and 2,009 deletions.
2 changes: 0 additions & 2 deletions gateway/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -127,9 +127,7 @@ func (g *GrpcLoadBalancer) Select(method string, args ...interface{}) (loadbalan
}
return nil, loadbalance.ErrNoEndpoint
}
func (g *GrpcLoadBalancer) Stats() {

}

type GrpcProxyMiddleware func(srv interface{}, serverStream grpc.ServerStream) error
type GrpcProxy struct {
Expand Down
2 changes: 0 additions & 2 deletions gateway/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -288,7 +287,6 @@ func (h *HttpEndpointImpl) inParamsHandle(pathParams map[string]string, req *htt
for k, v := range pathParams {
params[k] = []string{v}
}
log.Printf("%s,params:%v", req.URL.String(), params)
if len(params) > 0 {
return UrlQueryToProtoMessageField(in, params)
}
Expand Down
59 changes: 59 additions & 0 deletions gateway/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,17 @@ func testRegisterClient(t *testing.T) {
time.Sleep(2 * time.Second)
go gw.Start()
time.Sleep(4 * time.Second)
_, err = gw.proxyLB.Select("test/.test")
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, loadbalance.ErrNoEndpoint.Error())
})
}
func testRequestGet(t *testing.T) {
c.Convey("test request GET", t, func() {
url := fmt.Sprintf("http://127.0.0.1:%d/api/v1/example/world?msg=hello", gwPort)
r, err := http.NewRequest(http.MethodGet, url, nil)
r.Header.Set("x-uid", "12345678")
r.Header.Set(XAccessKey, "12345678")
// r.Header.Set("Origin", "http://www.example.com")
c.So(err, c.ShouldBeNil)

Expand Down Expand Up @@ -435,6 +439,42 @@ func testClientStreamRequestByMarshal(t *testing.T) {
for i := 0; i < 10; i++ {
c.So(reply.Replies[i].Message, c.ShouldEqual, fmt.Sprintf("hello-%d-%d", i, i))
}

marshal := NewProtobufWithLengthPrefix()
helloReq := &hello.HelloRequest{Msg: "hello", Name: "world"}
patch := gomonkey.ApplyFuncReturn(protojson.Marshal, nil, fmt.Errorf("test json marshal error"))
defer patch.Reset()
_, err = marshal.Marshal(helloReq)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "test json marshal error")
writer2 := &bytes.Buffer{}
encoder := marshal.NewEncoder(writer2)
in := &hello.HelloRequest{
Name: "world",
Msg: "hello",
}
err = encoder.Encode(in)
c.So(err, c.ShouldNotBeNil)
patch.Reset()

err = encoder.Encode(in)
c.So(err, c.ShouldBeNil)
decoder := marshal.NewDecoder(writer2)
patch2 := gomonkey.ApplyFuncReturn(binary.Read, fmt.Errorf("test json read error"))
defer patch2.Reset()
out := &hello.HelloRequest{}
err = decoder.Decode(out)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "test json read error")
patch2.Reset()

patch3 := gomonkey.ApplyFuncReturn((*bytes.Buffer).Read, 0, fmt.Errorf("test io read error"))
defer patch3.Reset()
err = decoder.Decode(out)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(), c.ShouldContainSubstring, "test io read error")
patch3.Reset()

})
}
func testDeleteEndpoint(t *testing.T) {
Expand Down Expand Up @@ -671,6 +711,12 @@ func testHttpError(t *testing.T) {
expectHttpCode: http.StatusGatewayTimeout,
expectInternalCode: int32(common.Code_TIMEOUT_ERROR),
},
{
code: int32(99999),
msg: codes.Internal.String(),
expectHttpCode: http.StatusInternalServerError,
expectInternalCode: int32(common.Code_INTERNAL_ERROR),
},
}
for _, v := range cases {
url := fmt.Sprintf("http://127.0.0.1:%d/api/v1/example/error/test?msg=ok&code=%d", gwPort, v.code)
Expand Down Expand Up @@ -764,30 +810,42 @@ func testServerSideEventErr(t *testing.T) {
cases := []struct {
patch interface{}
output []interface{}
err error
}{
{
patch: (*HttpEndpointImpl).inParamsHandle,
output: []interface{}{fmt.Errorf("test inParamsHandle error")},
err: fmt.Errorf("test inParamsHandle error"),
},
{
patch: (*httpForwardGrpcEndpointImpl).ServerSideStream,
output: []interface{}{nil, fmt.Errorf("test ServerSideStream error")},
err: fmt.Errorf("test ServerSideStream error"),
},
{
patch: (*serverSideStreamClient).Header,
output: []interface{}{nil, fmt.Errorf("test header error")},
err: fmt.Errorf("test header error"),
},
{
patch: (*goloadbalancer.ConnPool).Get,
output: []interface{}{nil, fmt.Errorf("test get conn error")},
err: fmt.Errorf("test get conn error"),
},
{
patch: (*grpc.ClientConn).NewStream,
output: []interface{}{nil, fmt.Errorf("test new stream error")},
err: fmt.Errorf("test new stream error"),
},
{
patch: (*serverSideStreamClient).SendMsg,
output: []interface{}{fmt.Errorf("test send error")},
err: fmt.Errorf("test send error"),
},
{
patch: protojson.Marshal,
output: []interface{}{nil, fmt.Errorf("test marshal error")},
err: fmt.Errorf("test marshal error"),
},
}
for _, caseV := range cases {
Expand All @@ -805,6 +863,7 @@ func testServerSideEventErr(t *testing.T) {
})
patch.Reset()
c.So(err, c.ShouldNotBeNil)
// c.So(err.Error(), c.ShouldContainSubstring, caseV.err.Error())
}
})
}
Expand Down
4 changes: 0 additions & 4 deletions gateway/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ func (l *LoggerImpl) WithFields(fields logrus.Fields) logger.Logger {
imp := &LoggerImpl{Entry: l.Entry.WithFields(fields)}
return imp
}
func (l *LoggerImpl) WithContext(ctx context.Context) logger.Logger {

return &LoggerImpl{Entry: l.Entry.WithContext(ctx)}
}
func (l *LoggerImpl) Logurs() *logrus.Logger {
return l.Logger
}
Expand Down
27 changes: 27 additions & 0 deletions gateway/logger_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package gateway

import (
"context"
"testing"

c "github.com/smartystreets/goconvey/convey"
)

func TestLog(t *testing.T) {
c.Convey("TestLog", t, func() {

Log.Info(context.Background(), "info")
Log.Warn(context.Background(), "warn")
Log.Infof(context.Background(), "infof")
Log.Debug(context.Background(), "debug")
Log.Debugf(context.Background(), "debugf")
Log.Logurs().Info("info")
Log.SetReportCaller(true)

loggerMid := NewLoggerMiddleware(Log)
loggerMid.SetPriority(2)
c.So(loggerMid.Priority(), c.ShouldEqual, 2)
c.So(loggerMid.Name(), c.ShouldEqual, "logger")

})
}
2 changes: 1 addition & 1 deletion gateway/middlewares.go
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ func HttpResponseBodyModify(ctx context.Context, w http.ResponseWriter, msg prot

}
writeHttpHeaders(w, key, value)
if strings.HasSuffix(http.CanonicalHeaderKey(key), "X-Http-Code") {
if strings.HasSuffix(http.CanonicalHeaderKey(key), http.CanonicalHeaderKey("X-Http-Code")) {
codeStr := value[0]
code, err := strconv.ParseInt(codeStr, 10, 32)
if err != nil {
Expand Down
11 changes: 11 additions & 0 deletions gateway/protobuf_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ func testSetHttpResponseErr(t *testing.T) {
os.Remove(filepath.Join(pbFile, "desc.pb"))
os.Remove(filepath.Join(pbFile, "json"))
pd, err := NewDescription(pbFile)

c.So(err, c.ShouldBeNil)
cases := []struct {
patch interface{}
Expand Down Expand Up @@ -76,6 +77,16 @@ func testSetHttpResponseErr(t *testing.T) {
c.So(err, c.ShouldNotBeNil)
patch.Reset()
}
patch:=gomonkey.ApplyFunc((*json.Decoder).Decode, func(_ *json.Decoder, v any) error {
val:=v.(*map[string]interface{})
(*val)["/SayHello"]=[]interface{}{map[string]interface{}{"OutName":"HttpBody"}}
return nil
})
defer patch.Reset()
err = pd.SetHttpResponse(common.E_HttpResponse)
c.So(err, c.ShouldNotBeNil)
c.So(err.Error(),c.ShouldContainSubstring,"invalid gateway.json")
patch.Reset()
})
}
func testNewDescriptionErr(t *testing.T) {
Expand Down
11 changes: 10 additions & 1 deletion gateway/serialization_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,16 @@ func TestRawBinaryUnmarshaler(t *testing.T) {
c.So(err2, c.ShouldBeNil)
c.So(marshal.ContentType(msg2), c.ShouldContainSubstring, "application/octet-stream-test")

c.So(decoder3.Decode(nil),c.ShouldBeNil)
c.So(decoder3.Decode(nil), c.ShouldBeNil)

patch1 := gomonkey.ApplyFuncReturn(proto.Marshal, nil, fmt.Errorf("proto.Marshal: nil"))
defer patch1.Reset()
c.So(marshal.ContentType(msg2), c.ShouldEqual, "application/octet-stream")
patch1.Reset()

patch2:=gomonkey.ApplyFuncReturn(proto.Unmarshal, fmt.Errorf("io.ReadAll: unexpected EOF"))
defer patch2.Reset()
c.So(marshal.ContentType(msg2), c.ShouldEqual, "application/octet-stream")
})
}

Expand Down
9 changes: 7 additions & 2 deletions gateway/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,19 @@ func (x *serverSideStreamClient)CloseSend()error{
func (x *clientSideStreamClient) Send(m protoreflect.ProtoMessage) error {
return x.ClientStream.SendMsg(m)
}

func (x *clientSideStreamClient) CloseSend() error {
return x.ClientStream.CloseSend()
}
func (x *clientSideStreamClient)RecvMsg(v any)error{
return x.ClientStream.RecvMsg(v)
}
func (x *clientSideStreamClient) CloseAndRecv() (protoreflect.ProtoMessage, error) {
if err := x.CloseSend(); err != nil {
return nil, err
}
out := dynamicpb.NewMessage(x.out)

if err := x.ClientStream.RecvMsg(out); err != nil {
if err := x.RecvMsg(out); err != nil {
return nil, err
}
return out, nil
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ require (
require (
github.com/agiledragon/gomonkey/v2 v2.11.0
github.com/begonia-org/go-loadbalancer v0.0.0-20240519060752-71ca464f0f1a
github.com/begonia-org/go-sdk v0.0.0-20240519143740-d09416b7b751
github.com/begonia-org/go-sdk v0.0.0-20240520034852-0b45d3942779
github.com/go-git/go-git/v5 v5.11.0
github.com/go-playground/validator/v10 v10.19.0
github.com/gorilla/websocket v1.5.0
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ github.com/begonia-org/go-sdk v0.0.0-20240517093020-2a19277f4cd0 h1:PRMFCCLybAmO
github.com/begonia-org/go-sdk v0.0.0-20240517093020-2a19277f4cd0/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y=
github.com/begonia-org/go-sdk v0.0.0-20240519143740-d09416b7b751 h1:ku84LpIO8hZ54BzE089pfTB1Op7YIA3GMLEcN49VoUI=
github.com/begonia-org/go-sdk v0.0.0-20240519143740-d09416b7b751/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y=
github.com/begonia-org/go-sdk v0.0.0-20240520034852-0b45d3942779 h1:iL/WWH9anPFbGJWYIhqPIcVAkWKfPq0HntG5NkHI2uk=
github.com/begonia-org/go-sdk v0.0.0-20240520034852-0b45d3942779/go.mod h1:I70a3fiAADGrOoOC3lv408rFcTRhTwLt3pwr6cQwB4Y=
github.com/bmatcuk/doublestar v1.1.1/go.mod h1:UD6OnuiIn0yFxxA2le/rnRU1G4RaI4UvFv1sNto9p6w=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
Expand Down
46 changes: 0 additions & 46 deletions internal/pkg/runtime/Makefile

This file was deleted.

41 changes: 0 additions & 41 deletions internal/pkg/runtime/coverprofile.cov

This file was deleted.

Loading

0 comments on commit 9f2bb43

Please sign in to comment.