加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
client.go 1.31 KB
一键复制 编辑 原始数据 按行查看 历史
lukeaxu 提交于 2023-11-10 13:14 . etcd implement
package discover
import (
"context"
"time"
"github.com/lukeaxu/discover/registry"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
)
type ClientOpt func(*Client)
type Client struct {
registry registry.Registry
insecure bool
timeout time.Duration
}
func ClientWithInsecure() ClientOpt {
return func(c *Client) {
c.insecure = true
}
}
func ClientWithRegistry(r registry.Registry, d time.Duration) ClientOpt {
return func(c *Client) {
c.registry = r
c.timeout = d
}
}
func NewClient(opts ...ClientOpt) (*Client, error) {
client := &Client{}
for _, opt := range opts {
opt(client)
}
return client, nil
}
func (c *Client) Dial(ctx context.Context, sn string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
var target = sn
dialOpts := make([]grpc.DialOption, 0)
if c.registry != nil {
rb, err := NewGrpcResolverBuilder(c.registry, c.timeout)
if err != nil {
return nil, err
}
dialOpts = append(dialOpts, grpc.WithResolvers(rb))
target = rb.targetForServiceName(sn)
}
if c.insecure {
dialOpts = append(dialOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if len(opts) > 0 {
dialOpts = append(dialOpts, opts...)
}
cc, err := grpc.DialContext(ctx, target, dialOpts...)
return cc, err
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化