-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathclient.go
92 lines (78 loc) · 2.18 KB
/
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
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
92
package cmd
import (
"context"
"time"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
frontierv1beta1 "github.com/raystack/frontier/proto/v1beta1"
"github.com/spf13/cobra"
"google.golang.org/grpc"
)
func createConnection(ctx context.Context, host string, caCertFile string) (*grpc.ClientConn, error) {
creds := insecure.NewCredentials()
if caCertFile != "" {
tlsCreds, err := credentials.NewClientTLSFromFile(caCertFile, "")
if err != nil {
return nil, err
}
creds = tlsCreds
}
opts := []grpc.DialOption{
grpc.WithTransportCredentials(creds),
grpc.WithBlock(),
}
return grpc.DialContext(ctx, host, opts...)
}
func createClient(ctx context.Context, host string) (frontierv1beta1.FrontierServiceClient, func(), error) {
dialTimeoutCtx, dialCancel := context.WithTimeout(ctx, time.Second*2)
conn, err := createConnection(dialTimeoutCtx, host, "")
if err != nil {
dialCancel()
return nil, nil, err
}
cancel := func() {
dialCancel()
conn.Close()
}
client := frontierv1beta1.NewFrontierServiceClient(conn)
return client, cancel, nil
}
func createAdminClient(ctx context.Context, host string) (frontierv1beta1.AdminServiceClient, func(), error) {
dialTimeoutCtx, dialCancel := context.WithTimeout(ctx, time.Second*2)
conn, err := createConnection(dialTimeoutCtx, host, "")
if err != nil {
dialCancel()
return nil, nil, err
}
cancel := func() {
dialCancel()
conn.Close()
}
client := frontierv1beta1.NewAdminServiceClient(conn)
return client, cancel, nil
}
func isClientCLI(cmd *cobra.Command) bool {
for c := cmd; c.Parent() != nil; c = c.Parent() {
if c.Annotations != nil && c.Annotations["client"] == "true" {
return true
}
}
return false
}
func overrideClientConfigHost(cmd *cobra.Command, cliConfig *Config) error {
if cliConfig == nil {
return ErrClientConfigNotFound
}
host, err := cmd.Flags().GetString("host")
if err == nil && host != "" {
cliConfig.Host = host
return nil
}
if cliConfig.Host == "" {
return ErrClientConfigHostNotFound
}
return nil
}
func bindFlagsFromClientConfig(cmd *cobra.Command) {
cmd.PersistentFlags().StringP("host", "h", "", "Frontier API service to connect to")
}