Fixing styling issues for caching.

This commit is contained in:
Burcu Dogan 2014-05-22 14:33:36 +02:00
parent 0476447419
commit 6bb3577bf0
3 changed files with 18 additions and 14 deletions

View File

@ -24,8 +24,11 @@ func NewFileCache(filename string) *FileCache {
// FileCache represents a file based token cacher. // FileCache represents a file based token cacher.
type FileCache struct { type FileCache struct {
filename string // Handler to be invoked if an error occurs
ErrorHandlerFunc func(error) // during read or write operations.
ErrorHandler func(error)
filename string
} }
// Read reads a cache token from the specified file. // Read reads a cache token from the specified file.
@ -34,8 +37,8 @@ func (f *FileCache) Read() (token *Token) {
if err == nil { if err == nil {
err = json.Unmarshal(data, token) err = json.Unmarshal(data, token)
} }
if f.ErrorHandlerFunc != nil { if f.ErrorHandler != nil {
f.ErrorHandlerFunc(err) f.ErrorHandler(err)
} }
return return
} }
@ -46,7 +49,7 @@ func (f *FileCache) Write(token *Token) {
if err == nil { if err == nil {
err = ioutil.WriteFile(f.filename, data, 0644) err = ioutil.WriteFile(f.filename, data, 0644)
} }
if f.ErrorHandlerFunc != nil { if f.ErrorHandler != nil {
f.ErrorHandlerFunc(err) f.ErrorHandler(err)
} }
} }

View File

@ -12,7 +12,7 @@ import (
func TestFileCacheErrorHandling(t *testing.T) { func TestFileCacheErrorHandling(t *testing.T) {
var lastErr error var lastErr error
fileCache := NewFileCache("/path/that/doesnt/exist") fileCache := NewFileCache("/path/that/doesnt/exist")
fileCache.ErrorHandlerFunc = func(err error) { fileCache.ErrorHandler = func(err error) {
lastErr = err lastErr = err
} }
fileCache.Read() fileCache.Read()

View File

@ -94,12 +94,14 @@ func NewAuthorizedTransport(fetcher TokenFetcher, token *Token) Transport {
// If token is expired, tries to refresh/fetch a new token. // If token is expired, tries to refresh/fetch a new token.
func (t *authorizedTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) { func (t *authorizedTransport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
token := t.Token() token := t.Token()
cache := t.fetcher.Cache()
if token == nil && cache != nil { // Try to initialize the token from the cache.
// Try to read from cache initially if token == nil {
token = cache.Read() if c := t.fetcher.Cache(); c != nil {
token = c.Read()
}
} }
if token == nil || token.Expired() { if token == nil || token.Expired() {
// Check if the token is refreshable. // Check if the token is refreshable.
// If token is refreshable, don't return an error, // If token is refreshable, don't return an error,
@ -165,9 +167,8 @@ func (t *authorizedTransport) RefreshToken() error {
} }
t.token = token t.token = token
cache := t.fetcher.Cache() if c := t.fetcher.Cache(); c != nil {
if cache != nil { c.Write(token)
cache.Write(token)
} }
return nil return nil