diff --git a/github/github.go b/github/github.go index e97e31f2f5..7d915dfa72 100644 --- a/github/github.go +++ b/github/github.go @@ -24,6 +24,7 @@ import ( "time" "github.com/google/go-querystring/query" + "golang.org/x/oauth2" ) const ( @@ -346,6 +347,11 @@ func NewClient(httpClient *http.Client) *Client { return c } +// NewTokenClient returns a new GitHub API client authenticated with the provided token. +func NewTokenClient(ctx context.Context, token string) *Client { + return NewClient(oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}))) +} + // NewEnterpriseClient returns a new GitHub API client with provided // base URL and upload URL (often is your GitHub Enterprise hostname). // If the base URL does not have the suffix "/api/v3/", it will be added automatically. diff --git a/github/github_test.go b/github/github_test.go index 53809399fa..50ecd5435b 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -22,6 +22,7 @@ import ( "time" "github.com/google/go-cmp/cmp" + "golang.org/x/oauth2" ) const ( @@ -266,6 +267,19 @@ func TestClient(t *testing.T) { } } +func TestNewTokenClient(t *testing.T) { + token := "gh_test_token" + ctx := context.Background() + c := NewTokenClient(ctx, token) + tr, ok := c.Client().Transport.(*oauth2.Transport) + if !ok { + t.Error("Client transport is not oauth2.Transport") + } + if tok, err := tr.Source.Token(); err != nil || tok.AccessToken != token { + t.Errorf("Client not using correct token") + } +} + func TestNewEnterpriseClient(t *testing.T) { baseURL := "https://custom-url/api/v3/" uploadURL := "https://custom-upload-url/api/uploads/"