github.com/crowdsecurity/crowdsec@v1.6.1/pkg/apiclient/auth_key.go (about)

     1  package apiclient
     2  
     3  import (
     4  	"errors"
     5  	"net/http"
     6  	"net/http/httputil"
     7  	"net/url"
     8  
     9  	log "github.com/sirupsen/logrus"
    10  )
    11  
    12  type APIKeyTransport struct {
    13  	APIKey string
    14  	// Transport is the underlying HTTP transport to use when making requests.
    15  	// It will default to http.DefaultTransport if nil.
    16  	Transport     http.RoundTripper
    17  	URL           *url.URL
    18  	VersionPrefix string
    19  	UserAgent     string
    20  }
    21  
    22  // RoundTrip implements the RoundTripper interface.
    23  func (t *APIKeyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
    24  	if t.APIKey == "" {
    25  		return nil, errors.New("APIKey is empty")
    26  	}
    27  
    28  	// We must make a copy of the Request so
    29  	// that we don't modify the Request we were given. This is required by the
    30  	// specification of http.RoundTripper.
    31  	req = cloneRequest(req)
    32  	req.Header.Add("X-Api-Key", t.APIKey)
    33  
    34  	if t.UserAgent != "" {
    35  		req.Header.Add("User-Agent", t.UserAgent)
    36  	}
    37  
    38  	log.Debugf("req-api: %s %s", req.Method, req.URL.String())
    39  
    40  	if log.GetLevel() >= log.TraceLevel {
    41  		dump, _ := httputil.DumpRequest(req, true)
    42  		log.Tracef("auth-api request: %s", string(dump))
    43  	}
    44  
    45  	// Make the HTTP request.
    46  	resp, err := t.transport().RoundTrip(req)
    47  	if err != nil {
    48  		log.Errorf("auth-api: auth with api key failed return nil response, error: %s", err)
    49  
    50  		return resp, err
    51  	}
    52  
    53  	if log.GetLevel() >= log.TraceLevel {
    54  		dump, _ := httputil.DumpResponse(resp, true)
    55  		log.Tracef("auth-api response: %s", string(dump))
    56  	}
    57  
    58  	log.Debugf("resp-api: http %d", resp.StatusCode)
    59  
    60  	return resp, err
    61  }
    62  
    63  func (t *APIKeyTransport) Client() *http.Client {
    64  	return &http.Client{Transport: t}
    65  }
    66  
    67  func (t *APIKeyTransport) transport() http.RoundTripper {
    68  	if t.Transport != nil {
    69  		return t.Transport
    70  	}
    71  
    72  	return http.DefaultTransport
    73  }