-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgrpc.go
80 lines (65 loc) · 1.46 KB
/
grpc.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
package seabird
import (
"context"
"crypto/x509"
"errors"
"fmt"
"net/url"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
func newGRPCClient(host, token string) (*grpc.ClientConn, error) {
newCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
url, err := url.Parse(host)
if err != nil {
return nil, err
}
var insecure bool
port := url.Port()
switch url.Scheme {
case "http":
insecure = true
if port == "" {
port = "80"
}
case "https":
if port == "" {
port = "443"
}
default:
return nil, errors.New("unknown grpc scheme")
}
var opt grpc.DialOption
if insecure {
opt = grpc.WithInsecure()
} else {
certPool, err := x509.SystemCertPool()
if err != nil {
return nil, err
}
opt = grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(certPool, ""))
}
conn, err := grpc.DialContext(newCtx, fmt.Sprintf("%s:%s", url.Hostname(), port),
opt,
grpc.WithPerRPCCredentials(grpcTokenAuth{
Token: token,
Insecure: insecure,
}),
grpc.WithBlock())
return conn, err
}
var _ credentials.PerRPCCredentials = (*grpcTokenAuth)(nil)
type grpcTokenAuth struct {
Token string
Insecure bool
}
func (a grpcTokenAuth) GetRequestMetadata(ctx context.Context, in ...string) (map[string]string, error) {
return map[string]string{
"Authorization": "Bearer " + a.Token,
}, nil
}
func (a grpcTokenAuth) RequireTransportSecurity() bool {
return !a.Insecure
}