gitlab.com/picnic-app/backend/role-api@v0.0.0-20230614140944-06a76ff3696d/internal/util/grpcclient/client.go (about) 1 package grpcclient 2 3 import ( 4 "context" 5 "crypto/tls" 6 "crypto/x509" 7 "fmt" 8 "log" 9 10 "google.golang.org/grpc" 11 "google.golang.org/grpc/credentials" 12 "google.golang.org/grpc/credentials/insecure" 13 14 "gitlab.com/picnic-app/backend/libs/golang/core/mw" 15 "gitlab.com/picnic-app/backend/libs/golang/logger" 16 "gitlab.com/picnic-app/backend/libs/golang/monitoring/tracing" 17 ) 18 19 type ( 20 ctxAppNameKey struct{} 21 ) 22 23 func New(ctx context.Context, host string, port int, secure bool, serviceName, secret string) *grpc.ClientConn { 24 addr := fmt.Sprintf("%s:%d", host, port) 25 cred := insecure.NewCredentials() 26 27 if secure { 28 systemRoots, err := x509.SystemCertPool() 29 if err != nil { 30 logger.Fatal(ctx, err) 31 } 32 cred = credentials.NewTLS(&tls.Config{ 33 MinVersion: tls.VersionTLS12, 34 MaxVersion: tls.VersionTLS13, 35 RootCAs: systemRoots, 36 }) 37 } 38 39 opts := []grpc.DialOption{ 40 grpc.WithTransportCredentials(cred), 41 grpc.WithChainUnaryInterceptor( 42 mw.NewClientContextInterceptor(serviceName, secret).Unary(), 43 tracing.ClientUnaryInterceptor(), 44 ), 45 grpc.WithChainStreamInterceptor( 46 mw.NewClientContextInterceptor(serviceName, secret).Stream(), 47 tracing.ClientStreamInterceptor(), 48 ), 49 grpc.WithUserAgent(serviceName), 50 } 51 52 conn, err := grpc.DialContext(context.WithValue(ctx, ctxAppNameKey{}, serviceName), addr, opts...) 53 if err != nil { 54 log.Fatalf("failed to create grpc client: %v", err) 55 } 56 return conn 57 }