-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
91 lines (78 loc) · 1.9 KB
/
plugin.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package plugin
import (
"context"
"crypto/tls"
"net/http"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)
type Options struct {
Token string
TLSConfig *tls.Config
Header http.Header
Timeout time.Duration
}
type Option func(opts *Options)
func TokenOption(token string) Option {
return func(opts *Options) {
opts.Token = token
}
}
func TLSConfigOption(cfg *tls.Config) Option {
return func(opts *Options) {
opts.TLSConfig = cfg
}
}
func HeaderOption(header http.Header) Option {
return func(opts *Options) {
opts.Header = header
}
}
func TimeoutOption(timeout time.Duration) Option {
return func(opts *Options) {
opts.Timeout = timeout
}
}
func NewGRPCConn(addr string, opts *Options) (*grpc.ClientConn, error) {
grpcOpts := []grpc.DialOption{
// grpc.WithBlock(),
grpc.WithConnectParams(grpc.ConnectParams{
Backoff: backoff.DefaultConfig,
}),
grpc.FailOnNonTempDialError(true),
}
if opts.TLSConfig != nil {
grpcOpts = append(grpcOpts,
grpc.WithAuthority(opts.TLSConfig.ServerName),
grpc.WithTransportCredentials(credentials.NewTLS(opts.TLSConfig)),
)
} else {
grpcOpts = append(grpcOpts, grpc.WithTransportCredentials(insecure.NewCredentials()))
}
if opts.Token != "" {
grpcOpts = append(grpcOpts, grpc.WithPerRPCCredentials(&rpcCredentials{token: opts.Token}))
}
return grpc.Dial(addr, grpcOpts...)
}
type rpcCredentials struct {
token string
}
func (c *rpcCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"token": c.token,
}, nil
}
func (c *rpcCredentials) RequireTransportSecurity() bool {
return false
}
func NewHTTPClient(opts *Options) *http.Client {
return &http.Client{
Timeout: opts.Timeout,
Transport: &http.Transport{
TLSClientConfig: opts.TLSConfig,
},
}
}