-
Notifications
You must be signed in to change notification settings - Fork 2
/
grpc.go
41 lines (35 loc) · 873 Bytes
/
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
package gosdk
import (
"context"
"crypto/tls"
"fmt"
"time"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
)
func GetGRPCConnection(
grpcUrl string, grpcInsecure bool, timeoutSeconds int64,
) (*grpc.ClientConn, error) {
var creds credentials.TransportCredentials
if grpcInsecure {
creds = insecure.NewCredentials()
} else {
creds = credentials.NewTLS(&tls.Config{})
}
options := []grpc.DialOption{
grpc.WithBlock(),
grpc.WithTransportCredentials(creds),
}
timeout := time.Duration(timeoutSeconds) * time.Second
ctx, cancel := context.WithTimeout(
context.Background(), timeout,
)
defer cancel()
conn, err := grpc.DialContext(ctx, grpcUrl, options...)
if err != nil {
return nil, fmt.Errorf(
"%w: Cannot connect to gRPC endpoint %s\n", err, grpcUrl)
}
return conn, nil
}