-
Notifications
You must be signed in to change notification settings - Fork 86
/
grpc_client.go
59 lines (49 loc) · 1.6 KB
/
grpc_client.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
package grpc_client
import (
"context"
"net/url"
"github.com/buildbuddy-io/buildbuddy/server/rpc/filters"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/google"
)
// DialTarget handles some of the logic around detecting the correct GRPC
// connection type and applying relevant options when connecting.
func DialTarget(target string) (*grpc.ClientConn, error) {
return DialTargetWithOptions(target, true)
}
func DialTargetWithOptions(target string, grpcsBytestream bool) (*grpc.ClientConn, error) {
dialOptions := []grpc.DialOption{
filters.GetUnaryClientInterceptor(),
filters.GetStreamClientInterceptor(),
}
u, err := url.Parse(target)
if err == nil {
if u.User != nil {
dialOptions = append(dialOptions, grpc.WithPerRPCCredentials(newRPCCredentials(u.User.String())))
}
if u.Scheme == "grpcs" || (u.Scheme == "bytestream" && grpcsBytestream) {
dialOptions = append(dialOptions, grpc.WithTransportCredentials(google.NewDefaultCredentials().TransportCredentials()))
} else {
dialOptions = append(dialOptions, grpc.WithInsecure())
}
target = u.Host
}
// Connect to host/port and create a new client
return grpc.Dial(target, dialOptions...)
}
type rpcCredentials struct {
authorization string
}
func newRPCCredentials(authorization string) *rpcCredentials {
return &rpcCredentials{
authorization: authorization,
}
}
func (c *rpcCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"authorization": c.authorization,
}, nil
}
func (c *rpcCredentials) RequireTransportSecurity() bool {
return false
}