Caches should return an error instead of invoking a handler.

This commit is contained in:
Burcu Dogan 2014-06-22 15:19:44 -07:00
parent 8387534dd5
commit ad322e7e30
4 changed files with 12 additions and 18 deletions

View File

@ -13,9 +13,9 @@ import (
// Cache represents a token cacher. // Cache represents a token cacher.
type Cache interface { type Cache interface {
// Reads a cached token. It may return nil if none is cached. // Reads a cached token. It may return nil if none is cached.
Read() (token *Token, err error) Read() (*Token, error)
// Write writes a token to the cache. // Write writes a token to the cache.
Write(token *Token) Write(*Token) error
} }
// NewFileCache creates a new file cache. // NewFileCache creates a new file cache.
@ -25,9 +25,6 @@ func NewFileCache(filename string) (cache *FileCache) {
// FileCache represents a file based token cacher. // FileCache represents a file based token cacher.
type FileCache struct { type FileCache struct {
// Handler to be invoked if an error occurs during writing.
ErrorHandler func(error)
filename string filename string
} }
@ -49,12 +46,10 @@ func (f *FileCache) Read() (token *Token, err error) {
} }
// Write writes a token to the specified file. // Write writes a token to the specified file.
func (f *FileCache) Write(token *Token) { func (f *FileCache) Write(token *Token) error {
data, err := json.Marshal(token) data, err := json.Marshal(token)
if err == nil { if err == nil {
err = ioutil.WriteFile(f.filename, data, 0644) err = ioutil.WriteFile(f.filename, data, 0644)
} }
if f.ErrorHandler != nil { return err
f.ErrorHandler(err)
}
} }

View File

@ -54,18 +54,16 @@ func TestFileCacheWrite(t *testing.T) {
} }
cache := NewFileCache(path.Join(dirName, "cache-file")) cache := NewFileCache(path.Join(dirName, "cache-file"))
cache.ErrorHandler = func(err error) { err = cache.Write(&Token{
if err != nil {
t.Fatalf("Cache write should have been succeeded succesfully, recieved %v", err)
}
}
cache.Write(&Token{
AccessToken: "abc123", AccessToken: "abc123",
TokenType: "Bearer", TokenType: "Bearer",
RefreshToken: "def789", RefreshToken: "def789",
}) })
if err != nil {
t.Errorf("Cache write should have been succeeded succesfully, recieved %v", err)
}
data, err := ioutil.ReadFile(cache.filename) data, err := ioutil.ReadFile(cache.filename)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -177,7 +177,7 @@ func (t *authorizedTransport) RefreshToken() error {
t.token = token t.token = token
if t.cache != nil { if t.cache != nil {
t.cache.Write(token) return t.cache.Write(token)
} }
return nil return nil

View File

@ -13,8 +13,9 @@ func (m *mockCache) Read() (token *Token, err error) {
return m.token, nil return m.token, nil
} }
func (m *mockCache) Write(token *Token) { func (m *mockCache) Write(token *Token) error {
m.token = token m.token = token
return nil
} }
type mockTokenFetcher struct{ token *Token } type mockTokenFetcher struct{ token *Token }