oauth2: perform caching ops at the transport level

This commit is contained in:
Burcu Dogan
2014-06-17 16:09:09 +02:00
parent 5c1195ac3f
commit 4337573be3
4 changed files with 16 additions and 36 deletions

View File

@@ -76,6 +76,9 @@ type Transport interface {
}
type authorizedTransport struct {
// Cache to persist changes to the token that
// authorizes the current transport.
cache Cache
fetcher TokenFetcher
token *Token
@@ -90,6 +93,15 @@ func NewAuthorizedTransport(fetcher TokenFetcher, token *Token) Transport {
return &authorizedTransport{fetcher: fetcher, token: token}
}
func NewAuthorizedTransportWithCache(fetcher TokenFetcher, cache Cache) (transport Transport, err error) {
var token *Token
if token, err = cache.Read(); err != nil {
return
}
transport = &authorizedTransport{fetcher: fetcher, cache: cache, token: token}
return
}
// RoundTrip authorizes the request with the existing token.
// If token is expired, tries to refresh/fetch a new token.
func (t *authorizedTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
@@ -160,8 +172,8 @@ func (t *authorizedTransport) RefreshToken() error {
}
t.token = token
if c := t.fetcher.Cache(); c != nil {
c.Write(token)
if t.cache != nil {
t.cache.Write(token)
}
return nil