/
grpc_option.go
51 lines (46 loc) · 1.2 KB
/
grpc_option.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package options
import (
"github.com/hyetpang/go-frame/internal/components/grpc"
"go.uber.org/fx"
)
// GRPC server,使用etcd作为服务发现时,需要先调用options.WithEtcd(),初始化一个etcd客户端
func WithGRPCServer(options ...grpcOption) Option {
gOptions := new(grpcOptions)
for _, o := range options {
o(gOptions)
}
fxOption := fx.Provide(grpc.NewServer)
if gOptions.etcd {
fxOption = fx.Provide(grpc.NewServerEtcd)
}
return func(o *Options) {
o.FxOptions = append(o.FxOptions, fxOption)
}
}
// GRPC client,使用etcd作为服务发现时,需要先调用options.WithEtcd(),初始化一个etcd客户端
func WithGRPCClient(options ...grpcOption) Option {
gOptions := new(grpcOptions)
for _, o := range options {
o(gOptions)
}
fxOption := fx.Provide(grpc.NewClient)
if gOptions.etcd {
fxOption = fx.Provide(grpc.NewClientEtcd)
}
return func(o *Options) {
o.FxOptions = append(o.FxOptions, fxOption)
}
}
// Grpc 选项参数
type (
grpcOptions struct {
etcd bool // 是否使用etcd作为服务发现
}
grpcOption func(*grpcOptions)
)
// 使用etcd作为服务发现
func GrpcOptionEtcd() grpcOption {
return func(gOption *grpcOptions) {
gOption.etcd = true
}
}