esxlib/api/cloud/client.go

39 lines
1.2 KiB
Go
Raw Normal View History

2023-06-24 19:57:08 +00:00
package cloud
import (
"context"
"crypto/tls"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)
type Client struct {
CloudClient
}
func NewClient(apiAddress, apiToken string, insecure bool) (*Client, error) {
clientInterceptor := func(ctx context.Context, method string, req interface{}, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
return invoker(ctx, method, req, reply, cc, opts...)
}
if apiToken != "" {
clientInterceptor = func(ctx context.Context, method string, req interface{}, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", apiToken)
return invoker(ctx, method, req, reply, cc, opts...)
}
}
// TODO: use tls verification.. but that means we would need to load our own certificates into the end device
creds := credentials.NewTLS(&tls.Config{InsecureSkipVerify: insecure})
conn, err := grpc.Dial(apiAddress, grpc.WithTransportCredentials(creds), grpc.WithUnaryInterceptor(clientInterceptor))
if err != nil {
return nil, err
}
return &Client{
CloudClient: NewCloudClient(conn),
}, nil
}