Skip to content

Commit 63c1dee

Browse files
authored
Add NewTokenClient (#2637)
Fixes: #2636.
1 parent 36c47d1 commit 63c1dee

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

github/github.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import (
2424
"time"
2525

2626
"github.com/google/go-querystring/query"
27+
"golang.org/x/oauth2"
2728
)
2829

2930
const (
@@ -346,6 +347,11 @@ func NewClient(httpClient *http.Client) *Client {
346347
return c
347348
}
348349

350+
// NewTokenClient returns a new GitHub API client authenticated with the provided token.
351+
func NewTokenClient(ctx context.Context, token string) *Client {
352+
return NewClient(oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})))
353+
}
354+
349355
// NewEnterpriseClient returns a new GitHub API client with provided
350356
// base URL and upload URL (often is your GitHub Enterprise hostname).
351357
// If the base URL does not have the suffix "/api/v3/", it will be added automatically.

github/github_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import (
2222
"time"
2323

2424
"github.com/google/go-cmp/cmp"
25+
"golang.org/x/oauth2"
2526
)
2627

2728
const (
@@ -266,6 +267,19 @@ func TestClient(t *testing.T) {
266267
}
267268
}
268269

270+
func TestNewTokenClient(t *testing.T) {
271+
token := "gh_test_token"
272+
ctx := context.Background()
273+
c := NewTokenClient(ctx, token)
274+
tr, ok := c.Client().Transport.(*oauth2.Transport)
275+
if !ok {
276+
t.Error("Client transport is not oauth2.Transport")
277+
}
278+
if tok, err := tr.Source.Token(); err != nil || tok.AccessToken != token {
279+
t.Errorf("Client not using correct token")
280+
}
281+
}
282+
269283
func TestNewEnterpriseClient(t *testing.T) {
270284
baseURL := "https://custom-url/api/v3/"
271285
uploadURL := "https://custom-upload-url/api/uploads/"

0 commit comments

Comments
 (0)