Skip to content

Commit

Permalink
feat: Added simple basic auth based http client support
Browse files Browse the repository at this point in the history
  • Loading branch information
langecode committed Jan 10, 2023
1 parent e642f0d commit e6059be
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions bitbucket/bitbucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,3 +250,38 @@ func (c *Client) GetPaged(ctx context.Context, api, path string, v interface{},
}
return c.Do(ctx, req, v)
}

// BasicAuthTransport supports creating a http client passing username/password as basic authentication header.
type BasicAuthTransport struct {
Username string
Password string
}

// RoundTrip implements the RoundTripper interface.
func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) {
req2 := setCredentialsAsHeaders(req, t.Username, t.Password)
return http.DefaultTransport.RoundTrip(req2)
}

func setCredentialsAsHeaders(req *http.Request, id, secret string) *http.Request {
// To set extra headers, we must make a copy of the Request so
// that we don't modify the Request we were given. This is required by the
// specification of http.RoundTripper.
//
// Since we are going to modify only req.Header here, we only need a deep copy
// of req.Header.
convertedRequest := new(http.Request)
*convertedRequest = *req
convertedRequest.Header = make(http.Header, len(req.Header))
for k, s := range req.Header {
convertedRequest.Header[k] = append([]string(nil), s...)
}
convertedRequest.SetBasicAuth(id, secret)
return convertedRequest
}

// Client returns an *http.Client that makes requests that are authenticated
// using HTTP Basic Authentication.
func (t *BasicAuthTransport) Client() *http.Client {
return &http.Client{Transport: t}
}

0 comments on commit e6059be

Please sign in to comment.