diff --git a/bitbucket/bitbucket.go b/bitbucket/bitbucket.go index 0b69ec5..8ba4ef6 100644 --- a/bitbucket/bitbucket.go +++ b/bitbucket/bitbucket.go @@ -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} +}