diff --git a/application/rpcserver.go b/application/rpcserver.go index 693daba..e067161 100644 --- a/application/rpcserver.go +++ b/application/rpcserver.go @@ -1,20 +1,13 @@ package application import ( - "context" "fmt" routing "github.com/gly-hub/fasthttp-routing" "github.com/gly-hub/toolbox/ip" - "github.com/gly-hub/toolbox/stringx" - jsoniter "github.com/json-iterator/go" "github.com/smallnest/rpcx/server" "github.com/team-dandelion/go-dandelion/config" - error_support "github.com/team-dandelion/go-dandelion/error-support" "github.com/team-dandelion/go-dandelion/logger" - "github.com/team-dandelion/go-dandelion/server/http" "github.com/team-dandelion/go-dandelion/server/rpcx" - "github.com/team-dandelion/go-dandelion/telemetry" - "reflect" ) var ( @@ -25,8 +18,8 @@ var ( type RpcClient struct { ClientName string - clientPool *rpcx.ClientPool - headerFunc func(ctx *routing.Context, header map[string]string) map[string]string + ClientPool *rpcx.ClientPool + HeaderFunc func(ctx *routing.Context, header map[string]string) map[string]string } func initRpcClient() { @@ -47,97 +40,12 @@ func initRpcClient() { } rpcClient = &RpcClient{ ClientName: config.Conf.RpcClient.ClientName, - clientPool: client, + ClientPool: client, } } func RegisterHeaderFunc(f func(ctx *routing.Context, header map[string]string) map[string]string) { - rpcClient.headerFunc = f -} - -// RpcCall rpc请求 -func RpcCall(ctx *routing.Context, serverName, funcName string, args interface{}, reply interface{}) error { - if rpcClient.clientPool == nil { - panic("请配置rpcx参数") - } - content, _ := jsoniter.MarshalToString(args) - var traceId string - if telemetry.GetSpanTraceId() != nil { - traceId = telemetry.GetSpanTraceId().(string) - } - requestHeader := map[string]string{ - "request_id": stringx.Strval(logger.GetRequestId()), - "span_trace_id": traceId, - "client_name": rpcClient.ClientName, - "content": content, - } - - requestHeader = rpcClient.headerFunc(ctx, requestHeader) - c := rpcx.Header().Set(context.Background(), requestHeader) - err := rpcClient.clientPool.Client().Call(c, serverName, funcName, args, reply) - if err != nil { - logger.Error("ServerName: ", serverName, ", FuncName: ", funcName, ", Err: ", err) - return &error_support.Error{Code: 5001, Msg: "服务器异常"} - } - - rv := reflect.ValueOf(reply) - if rv.Kind() == reflect.Ptr { - rv = rv.Elem() - } - if rv.FieldByName("Code").Int() != int64(0) { - return &error_support.Error{Code: int(rv.FieldByName("Code").Int()), Msg: rv.FieldByName("Msg").String()} - } - return nil -} - -// SRpcCall rpc请求拓展 -func SRpcCall(ctx *routing.Context, serverName, funcName string, args interface{}, reply interface{}) error { - if rpcClient.clientPool == nil { - panic("请配置rpcx参数") - } - var hc http.HttpController - if err := hc.ReadJson(ctx, args); err != nil { - return hc.Fail(ctx, &error_support.Error{Code: 5000, Msg: "数据解析失败"}) - } - - content, _ := jsoniter.MarshalToString(args) - var traceId string - if telemetry.GetSpanTraceId() != nil { - traceId = telemetry.GetSpanTraceId().(string) - } - requestHeader := map[string]string{ - "request_id": stringx.Strval(logger.GetRequestId()), - "span_trace_id": traceId, - "client_name": rpcClient.ClientName, - "content": content, - } - requestHeader = rpcClient.headerFunc(ctx, requestHeader) - c := rpcx.Header().Set(context.Background(), requestHeader) - err := rpcClient.clientPool.Client().Call(c, serverName, funcName, args, reply) - if err != nil { - logger.Error("ServerName: ", serverName, ", FuncName: ", funcName, ", Err: ", err) - return hc.Fail(ctx, &error_support.Error{Code: 5001, Msg: "服务器异常"}) - } - - rt := reflect.TypeOf(reply) - if rt.Kind() == reflect.Ptr { - rt = rt.Elem() - } - _, cOk := rt.FieldByName("Code") - _, mOk := rt.FieldByName("Msg") - if mOk && cOk { - rv := reflect.ValueOf(reply) - if rv.Kind() == reflect.Ptr { - rv = rv.Elem() - } - - if rv.FieldByName("Code").Int() != int64(0) { - return hc.Fail(ctx, &error_support.Error{Code: int(rv.FieldByName("Code").Int()), Msg: rv.FieldByName("Msg").String()}) - } - return hc.Success(ctx, reply, rv.FieldByName("Msg").String()) - } - - return hc.Success(ctx, reply, "") + rpcClient.HeaderFunc = f } func RegisterRpcPlugin(plugins ...server.Plugin) { @@ -174,3 +82,7 @@ func RpcServer(handler interface{}, auth ...rpcx.AuthFunc) { } rpcServer.Start() } + +func GetRpcClient() *RpcClient { + return rpcClient +} diff --git a/go.mod b/go.mod index b9dd911..283dc9e 100644 --- a/go.mod +++ b/go.mod @@ -156,5 +156,6 @@ require ( google.golang.org/grpc v1.53.0 // indirect google.golang.org/protobuf v1.29.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index d11499d..c6b3449 100644 --- a/go.sum +++ b/go.sum @@ -1199,6 +1199,8 @@ gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMy gopkg.in/gcfg.v1 v1.2.3/go.mod h1:yesOnuUOFQAhST5vPY4nbZsb/huCgGGXlipJsBn0b3o= gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22 h1:VpOs+IwYnYBaFnrNAeB8UUWtL3vEUnzSCL1nVjPhqrw= +gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= diff --git a/tools/rpccall/Makefile b/tools/rpccall/Makefile new file mode 100644 index 0000000..dad8da2 --- /dev/null +++ b/tools/rpccall/Makefile @@ -0,0 +1,4 @@ +proto: + protoc -I. -I${GOPATH}/src -I ../../ -I ./ \ + --gofast_out=. --gofast_opt=paths=source_relative \ + --rpcx_out=. --rpcx_opt=paths=source_relative *.proto diff --git a/tools/rpccall/lib.pb.go b/tools/rpccall/lib.pb.go new file mode 100644 index 0000000..20e1873 --- /dev/null +++ b/tools/rpccall/lib.pb.go @@ -0,0 +1,363 @@ +// Code generated by protoc-gen-gogo. DO NOT EDIT. +// source: lib.proto + +package rpccall + +import ( + fmt "fmt" + _ "github.com/gogo/protobuf/gogoproto" + proto "github.com/golang/protobuf/proto" + io "io" + math "math" + math_bits "math/bits" +) + +// Reference imports to suppress errors if they are not otherwise used. +var _ = proto.Marshal +var _ = fmt.Errorf +var _ = math.Inf + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the proto package it is being compiled against. +// A compilation error at this line likely means your copy of the +// proto package needs to be updated. +const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package + +type CommonResp struct { + Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"-"` + Msg string `protobuf:"bytes,2,opt,name=msg,proto3" json:"-"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` +} + +func (m *CommonResp) Reset() { *m = CommonResp{} } +func (m *CommonResp) String() string { return proto.CompactTextString(m) } +func (*CommonResp) ProtoMessage() {} +func (*CommonResp) Descriptor() ([]byte, []int) { + return fileDescriptor_bd3a4bf272509e0b, []int{0} +} +func (m *CommonResp) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *CommonResp) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_CommonResp.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *CommonResp) XXX_Merge(src proto.Message) { + xxx_messageInfo_CommonResp.Merge(m, src) +} +func (m *CommonResp) XXX_Size() int { + return m.Size() +} +func (m *CommonResp) XXX_DiscardUnknown() { + xxx_messageInfo_CommonResp.DiscardUnknown(m) +} + +var xxx_messageInfo_CommonResp proto.InternalMessageInfo + +func (m *CommonResp) GetCode() int32 { + if m != nil { + return m.Code + } + return 0 +} + +func (m *CommonResp) GetMsg() string { + if m != nil { + return m.Msg + } + return "" +} + +func init() { + proto.RegisterType((*CommonResp)(nil), "rpccall.CommonResp") +} + +func init() { proto.RegisterFile("lib.proto", fileDescriptor_bd3a4bf272509e0b) } + +var fileDescriptor_bd3a4bf272509e0b = []byte{ + // 185 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0xe2, 0xcc, 0xc9, 0x4c, 0xd2, + 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x2f, 0x2a, 0x48, 0x4e, 0x4e, 0xcc, 0xc9, 0x91, 0xd2, + 0x4d, 0xcf, 0x2c, 0xc9, 0x28, 0x4d, 0xd2, 0x4b, 0xce, 0xcf, 0xd5, 0x4f, 0xcf, 0x4f, 0xcf, 0xd7, + 0x07, 0xcb, 0x27, 0x95, 0xa6, 0x81, 0x79, 0x60, 0x0e, 0x98, 0x05, 0xd1, 0xa7, 0xe4, 0xc0, 0xc5, + 0xe5, 0x9c, 0x9f, 0x9b, 0x9b, 0x9f, 0x17, 0x94, 0x5a, 0x5c, 0x20, 0x24, 0xc9, 0xc5, 0x92, 0x9c, + 0x9f, 0x92, 0x2a, 0xc1, 0xa8, 0xc0, 0xa8, 0xc1, 0xea, 0xc4, 0xfa, 0xea, 0x9e, 0x3c, 0xa3, 0x6e, + 0x10, 0x58, 0x48, 0x48, 0x9c, 0x8b, 0x39, 0xb7, 0x38, 0x5d, 0x82, 0x49, 0x81, 0x51, 0x83, 0x13, + 0x26, 0x03, 0x12, 0x71, 0x72, 0x3b, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, + 0xe4, 0x18, 0x67, 0x3c, 0x96, 0x63, 0x88, 0x32, 0x41, 0x72, 0x42, 0x49, 0x6a, 0x62, 0xae, 0x6e, + 0x4a, 0x62, 0x5e, 0x4a, 0x6a, 0x4e, 0x66, 0x7e, 0x9e, 0x7e, 0x7a, 0x3e, 0x12, 0xa7, 0x24, 0x3f, + 0x3f, 0xa7, 0x58, 0x1f, 0xea, 0xf0, 0x24, 0x36, 0xb0, 0x83, 0x8c, 0x01, 0x01, 0x00, 0x00, 0xff, + 0xff, 0x2d, 0x29, 0xbc, 0x0f, 0xd5, 0x00, 0x00, 0x00, +} + +func (m *CommonResp) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *CommonResp) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *CommonResp) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.XXX_unrecognized != nil { + i -= len(m.XXX_unrecognized) + copy(dAtA[i:], m.XXX_unrecognized) + } + if len(m.Msg) > 0 { + i -= len(m.Msg) + copy(dAtA[i:], m.Msg) + i = encodeVarintLib(dAtA, i, uint64(len(m.Msg))) + i-- + dAtA[i] = 0x12 + } + if m.Code != 0 { + i = encodeVarintLib(dAtA, i, uint64(m.Code)) + i-- + dAtA[i] = 0x8 + } + return len(dAtA) - i, nil +} + +func encodeVarintLib(dAtA []byte, offset int, v uint64) int { + offset -= sovLib(v) + base := offset + for v >= 1<<7 { + dAtA[offset] = uint8(v&0x7f | 0x80) + v >>= 7 + offset++ + } + dAtA[offset] = uint8(v) + return base +} +func (m *CommonResp) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + if m.Code != 0 { + n += 1 + sovLib(uint64(m.Code)) + } + l = len(m.Msg) + if l > 0 { + n += 1 + l + sovLib(uint64(l)) + } + if m.XXX_unrecognized != nil { + n += len(m.XXX_unrecognized) + } + return n +} + +func sovLib(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozLib(x uint64) (n int) { + return sovLib(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *CommonResp) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLib + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: CommonResp: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: CommonResp: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Code", wireType) + } + m.Code = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLib + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Code |= int32(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Msg", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowLib + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthLib + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthLib + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Msg = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipLib(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthLib + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + m.XXX_unrecognized = append(m.XXX_unrecognized, dAtA[iNdEx:iNdEx+skippy]...) + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func skipLib(dAtA []byte) (n int, err error) { + l := len(dAtA) + iNdEx := 0 + depth := 0 + for iNdEx < l { + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowLib + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= (uint64(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + wireType := int(wire & 0x7) + switch wireType { + case 0: + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowLib + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + iNdEx++ + if dAtA[iNdEx-1] < 0x80 { + break + } + } + case 1: + iNdEx += 8 + case 2: + var length int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return 0, ErrIntOverflowLib + } + if iNdEx >= l { + return 0, io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + length |= (int(b) & 0x7F) << shift + if b < 0x80 { + break + } + } + if length < 0 { + return 0, ErrInvalidLengthLib + } + iNdEx += length + case 3: + depth++ + case 4: + if depth == 0 { + return 0, ErrUnexpectedEndOfGroupLib + } + depth-- + case 5: + iNdEx += 4 + default: + return 0, fmt.Errorf("proto: illegal wireType %d", wireType) + } + if iNdEx < 0 { + return 0, ErrInvalidLengthLib + } + if depth == 0 { + return iNdEx, nil + } + } + return 0, io.ErrUnexpectedEOF +} + +var ( + ErrInvalidLengthLib = fmt.Errorf("proto: negative length found during unmarshaling") + ErrIntOverflowLib = fmt.Errorf("proto: integer overflow") + ErrUnexpectedEndOfGroupLib = fmt.Errorf("proto: unexpected end of group") +) diff --git a/tools/rpccall/lib.proto b/tools/rpccall/lib.proto new file mode 100644 index 0000000..bd2b765 --- /dev/null +++ b/tools/rpccall/lib.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package rpccall; +option go_package = "github.com/team-dandelion/go-dandelion/tools/rpccall"; +import "github.com/gogo/protobuf/gogoproto/gogo.proto"; + +message CommonResp { + int32 code = 1 [(gogoproto.jsontag) = '-']; + string msg = 2 [(gogoproto.jsontag) = '-']; +} diff --git a/tools/rpccall/messagepack.go b/tools/rpccall/messagepack.go new file mode 100644 index 0000000..c5983bf --- /dev/null +++ b/tools/rpccall/messagepack.go @@ -0,0 +1,103 @@ +package rpccall + +import ( + "context" + routing "github.com/gly-hub/fasthttp-routing" + "github.com/gly-hub/toolbox/stringx" + jsoniter "github.com/json-iterator/go" + "github.com/team-dandelion/go-dandelion/application" + error_support "github.com/team-dandelion/go-dandelion/error-support" + "github.com/team-dandelion/go-dandelion/logger" + "github.com/team-dandelion/go-dandelion/server/http" + "github.com/team-dandelion/go-dandelion/server/rpcx" + "github.com/team-dandelion/go-dandelion/telemetry" + "reflect" +) + +// RpcCall rpc请求 +func RpcCall(ctx *routing.Context, serverName, funcName string, args interface{}, reply interface{}) error { + rpcClient := application.GetRpcClient() + + if rpcClient.ClientPool == nil { + panic("请配置rpcx参数") + } + content, _ := jsoniter.MarshalToString(args) + var traceId string + if telemetry.GetSpanTraceId() != nil { + traceId = telemetry.GetSpanTraceId().(string) + } + requestHeader := map[string]string{ + "request_id": stringx.Strval(logger.GetRequestId()), + "span_trace_id": traceId, + "client_name": rpcClient.ClientName, + "content": content, + } + + requestHeader = rpcClient.HeaderFunc(ctx, requestHeader) + c := rpcx.Header().Set(context.Background(), requestHeader) + err := rpcClient.ClientPool.Client().Call(c, serverName, funcName, args, reply) + if err != nil { + logger.Error("ServerName: ", serverName, ", FuncName: ", funcName, ", Err: ", err) + return &error_support.Error{Code: 5001, Msg: "服务器异常"} + } + + rv := reflect.ValueOf(reply) + if rv.Kind() == reflect.Ptr { + rv = rv.Elem() + } + if rv.FieldByName("Code").Int() != int64(0) { + return &error_support.Error{Code: int(rv.FieldByName("Code").Int()), Msg: rv.FieldByName("Msg").String()} + } + return nil +} + +// SRpcCall rpc请求拓展 +func SRpcCall(ctx *routing.Context, serverName, funcName string, args interface{}, reply interface{}) error { + rpcClient := application.GetRpcClient() + if rpcClient.ClientPool == nil { + panic("请配置rpcx参数") + } + var hc http.HttpController + if err := hc.ReadJson(ctx, args); err != nil { + return hc.Fail(ctx, &error_support.Error{Code: 5000, Msg: "数据解析失败"}) + } + + content, _ := jsoniter.MarshalToString(args) + var traceId string + if telemetry.GetSpanTraceId() != nil { + traceId = telemetry.GetSpanTraceId().(string) + } + requestHeader := map[string]string{ + "request_id": stringx.Strval(logger.GetRequestId()), + "span_trace_id": traceId, + "client_name": rpcClient.ClientName, + "content": content, + } + requestHeader = rpcClient.HeaderFunc(ctx, requestHeader) + c := rpcx.Header().Set(context.Background(), requestHeader) + err := rpcClient.ClientPool.Client().Call(c, serverName, funcName, args, reply) + if err != nil { + logger.Error("ServerName: ", serverName, ", FuncName: ", funcName, ", Err: ", err) + return hc.Fail(ctx, &error_support.Error{Code: 5001, Msg: "服务器异常"}) + } + + rt := reflect.TypeOf(reply) + if rt.Kind() == reflect.Ptr { + rt = rt.Elem() + } + _, cOk := rt.FieldByName("Code") + _, mOk := rt.FieldByName("Msg") + if mOk && cOk { + rv := reflect.ValueOf(reply) + if rv.Kind() == reflect.Ptr { + rv = rv.Elem() + } + + if rv.FieldByName("Code").Int() != int64(0) { + return hc.Fail(ctx, &error_support.Error{Code: int(rv.FieldByName("Code").Int()), Msg: rv.FieldByName("Msg").String()}) + } + return hc.Success(ctx, reply, rv.FieldByName("Msg").String()) + } + + return hc.Success(ctx, reply, "") +} diff --git a/tools/rpccall/proto.go b/tools/rpccall/proto.go new file mode 100644 index 0000000..5110e6d --- /dev/null +++ b/tools/rpccall/proto.go @@ -0,0 +1,81 @@ +package rpccall + +import ( + "context" + routing "github.com/gly-hub/fasthttp-routing" + "github.com/gly-hub/toolbox/stringx" + jsoniter "github.com/json-iterator/go" + "github.com/team-dandelion/go-dandelion/application" + error_support "github.com/team-dandelion/go-dandelion/error-support" + "github.com/team-dandelion/go-dandelion/logger" + "github.com/team-dandelion/go-dandelion/server/http" + "github.com/team-dandelion/go-dandelion/server/rpcx" + "github.com/team-dandelion/go-dandelion/telemetry" + "reflect" +) + +func SProtoCall(ctx *routing.Context, param interface{}, handler interface{}) error { + rpcClient := application.GetRpcClient() + if rpcClient.ClientPool == nil { + panic("请配置rpcx参数") + } + + var hc http.HttpController + refParam := reflect.ValueOf(param) + if refParam.Kind() != reflect.Ptr { + return hc.Fail(ctx, &error_support.Error{Code: 5000, Msg: "数据解析失败"}) + } + + if len(ctx.PostBody()) > 0 { + if err := hc.ReadJson(ctx, param); err != nil { + return hc.Fail(ctx, &error_support.Error{Code: 5000, Msg: "数据解析失败"}) + } + + } + + content, _ := jsoniter.MarshalToString(param) + var traceId string + if telemetry.GetSpanTraceId() != nil { + traceId = telemetry.GetSpanTraceId().(string) + } + requestHeader := map[string]string{ + "request_id": stringx.Strval(logger.GetRequestId()), + "span_trace_id": traceId, + "client_name": rpcClient.ClientName, + "content": content, + } + + requestHeader = rpcClient.HeaderFunc(ctx, requestHeader) + newCtx := rpcx.Header().Set(context.Background(), requestHeader) + refHandler := reflect.ValueOf(handler) + if refHandler.Kind() != reflect.Func { + return hc.Fail(ctx, &error_support.Error{Code: 5000, Msg: "WRONG handler"}) + } + + inParam := []reflect.Value{reflect.ValueOf(newCtx), refParam} + rets := refHandler.Call(inParam) + if !rets[1].IsNil() { + err := rets[1].Interface().(error) + return hc.Fail(ctx, &error_support.Error{Code: 5000, Msg: err.Error()}) + } + // 对rpc响应内容进行处理 + rt := reflect.TypeOf(rets[0].Interface()) + if rt.Kind() == reflect.Ptr { + rt = rt.Elem() + } + _, cOk := rt.FieldByName("Code") + _, mOk := rt.FieldByName("Msg") + if mOk && cOk { + rv := reflect.ValueOf(rets[0].Interface()) + if rv.Kind() == reflect.Ptr { + rv = rv.Elem() + } + + if rv.FieldByName("Code").Int() != int64(0) { + return hc.Fail(ctx, &error_support.Error{Code: int(rv.FieldByName("Code").Int()), Msg: rv.FieldByName("Msg").String()}) + } + return hc.Success(ctx, rets[0].Interface(), rv.FieldByName("Msg").String()) + } + + return hc.Success(ctx, rets[0].Interface(), "") +}