1 Star 0 Fork 0

csingo / cRpc

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
GrpcController.go 923 Bytes
一键复制 编辑 原始数据 按行查看 历史
joe 提交于 2023-12-14 09:55 . update
package cRpc
import (
"context"
"errors"
"reflect"
"google.golang.org/grpc/metadata"
"gitee.com/csingo/cContext"
)
func GrpcHandler[Q, T any](ctx context.Context, app, service, method string, req Q, rsp T) (err error) {
instance := GetService(app, service)
if instance == nil {
return errors.New("rpc 服务异常")
}
caller := reflect.ValueOf(instance).MethodByName(method)
if !caller.IsValid() {
return errors.New("rpc 服务方法不存在")
}
// 读取上下文数据
newCtx := cContext.New()
if md, ok := metadata.FromIncomingContext(ctx); ok {
for k, v := range md {
var item string
if len(v) > 0 {
item = v[0]
}
newCtx.Header(k, item)
}
}
responseValues := caller.Call([]reflect.Value{reflect.ValueOf(newCtx), reflect.ValueOf(req)})
if !responseValues[1].IsNil() {
return responseValues[1].Interface().(error)
}
rsp = responseValues[0].Interface().(T)
return
}
Go
1
https://gitee.com/csingo/cRpc.git
git@gitee.com:csingo/cRpc.git
csingo
cRpc
cRpc
v0.2.52

搜索帮助