github.com/vnpaycloud-console/gophercloud/v2@v2.0.5/openstack/config/provider_client.go (about)

     1  package config
     2  
     3  import (
     4  	"context"
     5  	"crypto/tls"
     6  	"net/http"
     7  
     8  	"github.com/vnpaycloud-console/gophercloud/v2"
     9  	"github.com/vnpaycloud-console/gophercloud/v2/openstack"
    10  )
    11  
    12  type options struct {
    13  	httpClient http.Client
    14  	tlsConfig  *tls.Config
    15  }
    16  
    17  // WithHTTPClient enables passing a custom http.Client to be used in the
    18  // ProviderClient for authentication and for any further call, for example when
    19  // using a ServiceClient derived from this ProviderClient.
    20  func WithHTTPClient(httpClient http.Client) func(*options) {
    21  	return func(o *options) {
    22  		o.httpClient = httpClient
    23  	}
    24  }
    25  
    26  // WithTLSConfig replaces the Transport of the default HTTP client (or of the
    27  // HTTP client passed with WithHTTPClient) with a RoundTripper containing the
    28  // given TLS config.
    29  func WithTLSConfig(tlsConfig *tls.Config) func(*options) {
    30  	return func(o *options) {
    31  		o.tlsConfig = tlsConfig
    32  	}
    33  }
    34  
    35  // NewProviderClient logs in to an OpenStack cloud found at the identity
    36  // endpoint specified by the options, acquires a token, and returns a Provider
    37  // Client instance that's ready to operate.
    38  //
    39  // If the full path to a versioned identity endpoint was specified  (example:
    40  // http://example.com:5000/v3), that path will be used as the endpoint to
    41  // query.
    42  //
    43  // If a versionless endpoint was specified (example: http://example.com:5000/),
    44  // the endpoint will be queried to determine which versions of the identity
    45  // service are available, then chooses the most recent or most supported
    46  // version.
    47  func NewProviderClient(ctx context.Context, authOptions gophercloud.AuthOptions, opts ...func(*options)) (*gophercloud.ProviderClient, error) {
    48  	var options options
    49  	for _, apply := range opts {
    50  		apply(&options)
    51  	}
    52  
    53  	client, err := openstack.NewClient(authOptions.IdentityEndpoint)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  
    58  	if options.tlsConfig != nil {
    59  		transport := http.DefaultTransport.(*http.Transport).Clone()
    60  		transport.TLSClientConfig = options.tlsConfig
    61  		options.httpClient.Transport = transport
    62  	}
    63  	client.HTTPClient = options.httpClient
    64  
    65  	err = openstack.Authenticate(ctx, client, authOptions)
    66  	if err != nil {
    67  		return nil, err
    68  	}
    69  	return client, nil
    70  }