Repository navigation
Expand file tree
/
Copy pathconvert.go
More file actions
71 lines (59 loc) · 2.54 KB
/
Copy pathconvert.go
File metadata and controls
71 lines (59 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package oauthctx
import (
"context"
"golang.org/x/oauth2"
)
// Oauth2TokenSourceWithContext is the interface satisfied by types in
// golang.org/x/oauth2 (for example, clientcredentials.Config) whose Token
// method accepts a context. Implement this interface to use
// [AdoptTokenSourceWithContext].
type Oauth2TokenSourceWithContext interface {
Token(ctx context.Context) (*oauth2.Token, error)
}
// NewOauth2Token is a factory func, which implements Oauth2TokenSourceWithContext
type NewOauth2Token func(ctx context.Context) (*oauth2.Token, error)
// Token implements Oauth2TokenSourceWithContext
func (n NewOauth2Token) Token(ctx context.Context) (*oauth2.Token, error) {
return n(ctx)
}
// AdoptTokenSourceWithContext wraps any [Oauth2TokenSourceWithContext] (for
// example, clientcredentials.Config) as an oauthctx [TokenSource], forwarding
// ctx to the underlying Token call. Pair with [ReuseTokenSource] to add
// caching; or use [NewClient] which adds caching automatically.
func AdoptTokenSourceWithContext(src Oauth2TokenSourceWithContext, ops ...TokenSourceOp) TokenSource {
return &adoptedTokenSourcer{
new: src,
conf: NewTokenSourceConfig(ops...),
}
}
// Oauth2TokenConfig is the interface satisfied by types whose TokenSource
// method accepts a context and returns an oauth2.TokenSource. Implement this
// interface to use [AdoptTokenConfig].
type Oauth2TokenConfig interface {
TokenSource(ctx context.Context) oauth2.TokenSource
}
// NewOauth2TokenSource is a factory func, which implements Oauth2TokenConfig
type NewOauth2TokenSource func(ctx context.Context) oauth2.TokenSource
// TokenSource implements Oauth2TokenConfig
func (n NewOauth2TokenSource) TokenSource(ctx context.Context) oauth2.TokenSource {
return n(ctx)
}
// AdoptTokenConfig wraps any [Oauth2TokenConfig] as an oauthctx [TokenSource]
// by calling its TokenSource factory with ctx and then fetching the token.
// Use this for types that expose a TokenSource constructor rather than a direct
// Token method; for types that have both, prefer [AdoptTokenSourceWithContext].
func AdoptTokenConfig(src Oauth2TokenConfig, ops ...TokenSourceOp) TokenSource {
return &adoptedTokenSourcer{
new: NewOauth2Token(func(ctx context.Context) (*oauth2.Token, error) {
return src.TokenSource(ctx).Token()
}),
conf: NewTokenSourceConfig(ops...),
}
}
type adoptedTokenSourcer struct {
new Oauth2TokenSourceWithContext
conf *TokenSourceConfig
}
func (c *adoptedTokenSourcer) TokenContext(ctx context.Context) (*oauth2.Token, error) {
return c.new.Token(c.conf.WithOauth2HTTPClient(ctx))
}