github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/backend/remote-state/azure/sender.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package azure
     5  
     6  import (
     7  	"log"
     8  	"net/http"
     9  	"net/http/httputil"
    10  
    11  	"github.com/Azure/go-autorest/autorest"
    12  	"github.com/terramate-io/tf/logging"
    13  )
    14  
    15  func buildSender() autorest.Sender {
    16  	return autorest.DecorateSender(&http.Client{
    17  		Transport: &http.Transport{
    18  			Proxy: http.ProxyFromEnvironment,
    19  		},
    20  	}, withRequestLogging())
    21  }
    22  
    23  func withRequestLogging() autorest.SendDecorator {
    24  	return func(s autorest.Sender) autorest.Sender {
    25  		return autorest.SenderFunc(func(r *http.Request) (*http.Response, error) {
    26  			// only log if logging's enabled
    27  			logLevel := logging.CurrentLogLevel()
    28  			if logLevel == "" {
    29  				return s.Do(r)
    30  			}
    31  
    32  			// strip the authorization header prior to printing
    33  			authHeaderName := "Authorization"
    34  			auth := r.Header.Get(authHeaderName)
    35  			if auth != "" {
    36  				r.Header.Del(authHeaderName)
    37  			}
    38  
    39  			// dump request to wire format
    40  			if dump, err := httputil.DumpRequestOut(r, true); err == nil {
    41  				log.Printf("[DEBUG] Azure Backend Request: \n%s\n", dump)
    42  			} else {
    43  				// fallback to basic message
    44  				log.Printf("[DEBUG] Azure Backend Request: %s to %s\n", r.Method, r.URL)
    45  			}
    46  
    47  			// add the auth header back
    48  			if auth != "" {
    49  				r.Header.Add(authHeaderName, auth)
    50  			}
    51  
    52  			resp, err := s.Do(r)
    53  			if resp != nil {
    54  				// dump response to wire format
    55  				if dump, err2 := httputil.DumpResponse(resp, true); err2 == nil {
    56  					log.Printf("[DEBUG] Azure Backend Response for %s: \n%s\n", r.URL, dump)
    57  				} else {
    58  					// fallback to basic message
    59  					log.Printf("[DEBUG] Azure Backend Response: %s for %s\n", resp.Status, r.URL)
    60  				}
    61  			} else {
    62  				log.Printf("[DEBUG] Request to %s completed with no response", r.URL)
    63  			}
    64  			return resp, err
    65  		})
    66  	}
    67  }