1 回答
TA贡献1776条经验 获得超12个赞
得到它的工作,感谢protoreflect
没有错误处理的工作样本
//Parse protofile, create grpc.ServiceDesc, register
func (s *GRPCService) LoadSpec(protoFileName string) {
p := protoparse.Parser{}
fdlist, _ := p.ParseFiles(protoFileName)
for _, fd := range fdlist {
for _, rsd := range fd.GetServices() {
s.sdMap[rsd.GetName()] = rsd
gsd := grpc.ServiceDesc{ServiceName: rsd.GetName(), HandlerType: (*interface{})(nil)}
for _, m := range rsd.GetMethods() {
gsd.Methods = append(gsd.Methods, grpc.MethodDesc{MethodName: m.GetName(), Handler: s.Handler})
}
s.grpcServer.RegisterService(&gsd, s)
}
}
}
func (s *GRPCService) Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
stream := grpc.ServerTransportStreamFromContext(ctx)
arr := strings.Split(stream.Method(), "/")
serviceName := arr[1]
methodName := arr[2]
service := s.sdMap[serviceName]
method := service.FindMethodByName(methodName)
input := dynamic.NewMessage(method.GetInputType())
dec(input)
jsonInput, err := input.MarshalJSON()
log.Printf("Input:%s Err:%v \n", jsonInput, err)
//jsonOutput:=invokeServiceViaReflectionOrHttp(jsonInput)
jsonOutput := `{"message":"response"}`
output := dynamic.NewMessage(method.GetOutputType())
output.UnmarshalJSON([]byte(jsonOutput))
return output, nil
}
- 1 回答
- 0 关注
- 101 浏览
添加回答
举报