golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/buildgo/client.go (about)

     1  // Copyright 2018 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package buildgo
     6  
     7  import (
     8  	"context"
     9  	"net/http"
    10  	"sync"
    11  
    12  	"golang.org/x/build/buildenv"
    13  	"golang.org/x/oauth2"
    14  	"golang.org/x/oauth2/google"
    15  	compute "google.golang.org/api/compute/v1"
    16  )
    17  
    18  // Client is an authenticated client to the Go build system.
    19  type Client struct {
    20  	Env    *buildenv.Environment // generally Production or Staging
    21  	Creds  *google.Credentials
    22  	Client *http.Client // OAuth2 client
    23  
    24  	Verbose bool // enable extra debug logging
    25  
    26  	mu             sync.Mutex
    27  	computeService *compute.Service // lazily initialized
    28  }
    29  
    30  // NewClient returns a new client for using the Go build system in the provided environment.
    31  // The authentication information is discovered using env.Credentials.
    32  func NewClient(ctx context.Context, env *buildenv.Environment) (*Client, error) {
    33  	creds, err := env.Credentials(ctx)
    34  	if err != nil {
    35  		return nil, err
    36  	}
    37  	c := &Client{Env: env, Creds: creds}
    38  	c.Client = oauth2.NewClient(ctx, creds.TokenSource)
    39  	return c, nil
    40  }
    41  
    42  // Compute returns the GCE compute service.
    43  func (c *Client) Compute() *compute.Service {
    44  	c.mu.Lock()
    45  	defer c.mu.Unlock()
    46  	if c.computeService == nil {
    47  		c.computeService, _ = compute.New(c.Client)
    48  	}
    49  	return c.computeService
    50  }