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.
type Cache interface {
// 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(token *Token)
Write(*Token) error
}
// NewFileCache creates a new file cache.
@ -25,9 +25,6 @@ func NewFileCache(filename string) (cache *FileCache) {
// FileCache represents a file based token cacher.
type FileCache struct {
// Handler to be invoked if an error occurs during writing.
ErrorHandler func(error)
filename string
}
@ -49,12 +46,10 @@ func (f *FileCache) Read() (token *Token, err error) {
}
// 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)
if err == nil {
err = ioutil.WriteFile(f.filename, data, 0644)
}
if f.ErrorHandler != nil {
f.ErrorHandler(err)
}
return err
}

View File

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

View File

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

View File

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