package {{.PackageName}} import ( "context" "fmt" "log" "reflect" "github.com/nacos-group/nacos-sdk-go/v2/clients/naming_client" "github.com/nacos-group/nacos-sdk-go/v2/vo" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" ) var namingClient naming_client.INamingClient var groupName string // AutoGrpcInit auto grpc 必须调用初始化 func AutoGrpcInit(obj any) { value := reflect.ValueOf(obj) if value.Kind() == reflect.Ptr { value = value.Elem() } groupName = value.FieldByName("GroupName").String() for i := 0; i < value.NumField(); i++ { v := value.Field(i) if v.IsValid() { _namingClient, ok := v.Interface().(naming_client.INamingClient) if ok { namingClient = _namingClient } } } } {{range .ClientParams}} func Auto{{.ClientName}}Client(ctx context.Context) {{.ClientName}}Client { if namingClient == nil { log.Println("nameClient must be init. call") return nil } sel := vo.SelectOneHealthInstanceParam{ ServiceName: "{{.GrpcServiceName}}", GroupName: groupName, } insService, err := namingClient.SelectOneHealthyInstance(sel) if err != nil { log.Println(err) return nil } conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", insService.Ip, insService.Port), grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Println(err) return nil } return New{{.ClientName}}Client(conn) } func Auto{{.ClientName}}ClientEx(ctx context.Context, opts ...grpc.DialOption) ({{.ClientName}}Client,error) { if namingClient == nil { return nil, fmt.Errorf("nameClient must be init. call") } sel := vo.SelectOneHealthInstanceParam{ ServiceName: "{{.GrpcServiceName}}", GroupName: groupName, } insService, err := namingClient.SelectOneHealthyInstance(sel) if err != nil { return nil, err } conn, err := grpc.DialContext(ctx, fmt.Sprintf("%s:%d", insService.Ip, insService.Port), opts...) if err != nil { return nil, err } return New{{.ClientName}}Client(conn), nil } {{end}}