Skip to content

Commit

Permalink
update http client to support token auth
Browse files Browse the repository at this point in the history
  • Loading branch information
gondor committed Jul 15, 2017
1 parent cb3d9f0 commit 5d654d2
Showing 1 changed file with 11 additions and 4 deletions.
15 changes: 11 additions & 4 deletions httpclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"time"
"github.com/ContainX/go-utils/encoding"
"github.com/ContainX/go-utils/logger"
"fmt"
)

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

// Post the data against the specified url and unmarshal the
// response into the result if it is not nil
Post(url string, data interface{}, result interface{})
Post(url string, data interface{}, result interface{}) *Response
}

var (
Expand All @@ -98,15 +101,15 @@ func NewDefaultConfig() *HttpClientConfig {
}

// DefaultHttpClient provides a basic default http client
func DefaultHttpClient() *httpClient {
func DefaultHttpClient() HttpClient {
return NewHttpClient(*NewDefaultConfig())
}

func NewHttpClient(config HttpClientConfig) *httpClient {
func NewHttpClient(config HttpClientConfig) HttpClient {
hc := &httpClient{
config: config,
http: &http.Client{
Timeout: (time.Duration(config.RequestTimeout) * time.Second),
Timeout: time.Duration(config.RequestTimeout) * time.Second,
},
}
if config.TLSInsecureSkipVerify {
Expand Down Expand Up @@ -267,4 +270,8 @@ func addAuthentication(c HttpClientConfig, req *http.Request) {
if c.HttpUser != "" {
req.SetBasicAuth(c.HttpUser, c.HttpPass)
}

if c.AccessToken != "" {
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.AccessToken))
}
}

0 comments on commit 5d654d2

Please sign in to comment.