Skip to content

Commit 5d654d2

Browse files
committed
update http client to support token auth
1 parent cb3d9f0 commit 5d654d2

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

httpclient/client.go

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"time"
1212
"github.com/ContainX/go-utils/encoding"
1313
"github.com/ContainX/go-utils/logger"
14+
"fmt"
1415
)
1516

1617
var log = logger.GetLogger("httpclient")
@@ -45,6 +46,8 @@ type HttpClientConfig struct {
4546
HttpUser string
4647
// Http Basic Auth Password
4748
HttpPass string
49+
// Access Token will be applied to all requests if set
50+
AccessToken string
4851
// Request timeout
4952
RequestTimeout int
5053
// TLS Insecure Skip Verify
@@ -73,7 +76,7 @@ type HttpClient interface {
7376

7477
// Post the data against the specified url and unmarshal the
7578
// response into the result if it is not nil
76-
Post(url string, data interface{}, result interface{})
79+
Post(url string, data interface{}, result interface{}) *Response
7780
}
7881

7982
var (
@@ -98,15 +101,15 @@ func NewDefaultConfig() *HttpClientConfig {
98101
}
99102

100103
// DefaultHttpClient provides a basic default http client
101-
func DefaultHttpClient() *httpClient {
104+
func DefaultHttpClient() HttpClient {
102105
return NewHttpClient(*NewDefaultConfig())
103106
}
104107

105-
func NewHttpClient(config HttpClientConfig) *httpClient {
108+
func NewHttpClient(config HttpClientConfig) HttpClient {
106109
hc := &httpClient{
107110
config: config,
108111
http: &http.Client{
109-
Timeout: (time.Duration(config.RequestTimeout) * time.Second),
112+
Timeout: time.Duration(config.RequestTimeout) * time.Second,
110113
},
111114
}
112115
if config.TLSInsecureSkipVerify {
@@ -267,4 +270,8 @@ func addAuthentication(c HttpClientConfig, req *http.Request) {
267270
if c.HttpUser != "" {
268271
req.SetBasicAuth(c.HttpUser, c.HttpPass)
269272
}
273+
274+
if c.AccessToken != "" {
275+
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.AccessToken))
276+
}
270277
}

0 commit comments

Comments
 (0)