package authsvr
type AuthClient interface {
}
package handler
func TestInitRpcClient(t *testing.T) {
var authclent authsvr.AuthClient
InitMicroRpcClient(":9001", authsvr.NewAuthClient, &authclent)
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
u := &authsvr.User{
Username: "xxxx",
}
res, err := authclent.GetUser(ctx, u)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(res)
}
func InitMicroRpcClient(serverName string, clientNewfunc interface{}, target interface{}) {
log.Infof(context.Background(), "尝试创建grpc连接...: %v", serverName)
conn, err := grpc.Dial(serverName, grpc.WithBlock(), grpc.WithInsecure())
if err != nil {
log.Errorf(context.Background(), "connect rpc server failed, %v", err)
panic("connect rpc server failed")
}
log.Infof(context.Background(), "创建grpc连接成功...: %v", serverName)
fnValue := reflect.ValueOf(clientNewfunc)
if fnValue.Kind() != reflect.Func {
panic("InitMicroRpcClient clientNewfunc is not fun")
}
fnCallback := fnValue.Call([]reflect.Value{reflect.ValueOf(conn)})
if len(fnCallback) == 0 {
panic("InitMicroRpcClient func call fail")
}
if reflect.ValueOf(target).Kind() != reflect.Ptr {
panic("InitMicroRpcClient target is not ptr")
}
reflect.ValueOf(target).Elem().Set(fnCallback[0])
}
|