github.com/opentofu/opentofu@v1.7.1/internal/httpclient/useragent.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package httpclient
     7  
     8  import (
     9  	"fmt"
    10  	"log"
    11  	"net/http"
    12  	"os"
    13  	"strings"
    14  )
    15  
    16  const (
    17  	appendUaEnvVar         = "TF_APPEND_USER_AGENT"
    18  	customUaEnvVar         = "OPENTOFU_USER_AGENT"
    19  	DefaultApplicationName = "OpenTofu"
    20  )
    21  
    22  type userAgentRoundTripper struct {
    23  	inner     http.RoundTripper
    24  	userAgent string
    25  }
    26  
    27  func (rt *userAgentRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
    28  	if _, ok := req.Header["User-Agent"]; !ok {
    29  		req.Header.Set("User-Agent", rt.userAgent)
    30  	}
    31  	log.Printf("[TRACE] HTTP client %s request to %s", req.Method, req.URL.String())
    32  	return rt.inner.RoundTrip(req)
    33  }
    34  
    35  func OpenTofuUserAgent(version string) string {
    36  	ua := fmt.Sprintf("%s/%s", DefaultApplicationName, version)
    37  	if customUa := os.Getenv(customUaEnvVar); customUa != "" {
    38  		ua = customUa
    39  		log.Printf("[DEBUG] Using Custom User-Agent: %s", ua)
    40  	}
    41  
    42  	if add := os.Getenv(appendUaEnvVar); add != "" {
    43  		add = strings.TrimSpace(add)
    44  		if len(add) > 0 {
    45  			ua += " " + add
    46  			log.Printf("[DEBUG] Using modified User-Agent: %s", ua)
    47  		}
    48  	}
    49  
    50  	return ua
    51  }