Cache read operation should be handled during construction.

This commit is contained in:
Burcu Dogan
2014-05-26 11:53:51 +02:00
parent 6bb3577bf0
commit 909f098dcd
3 changed files with 91 additions and 30 deletions

View File

@@ -7,19 +7,34 @@ package oauth2
import (
"encoding/json"
"io/ioutil"
"os"
)
// Cache represents a token cacher.
type Cache interface {
// Read reads a cache token from the specified file.
Read() (token *Token)
// Token returns the initial token retrieved from the cache,
// if there is no existing token nil value is returned.
Token() (token *Token)
// Write writes a token to the specified file.
Write(token *Token)
}
// NewFileCache creates a new file cache.
func NewFileCache(filename string) *FileCache {
return &FileCache{filename: filename}
func NewFileCache(filename string) (cache *FileCache, err error) {
data, err := ioutil.ReadFile(filename)
if os.IsNotExist(err) {
// no token has cached before, skip reading
return &FileCache{filename: filename}, nil
}
if err != nil {
return
}
var token Token
if err = json.Unmarshal(data, &token); err != nil {
return
}
cache = &FileCache{filename: filename, initialToken: &token}
return
}
// FileCache represents a file based token cacher.
@@ -28,19 +43,15 @@ type FileCache struct {
// during read or write operations.
ErrorHandler func(error)
filename string
initialToken *Token
filename string
}
// Read reads a cache token from the specified file.
func (f *FileCache) Read() (token *Token) {
data, err := ioutil.ReadFile(f.filename)
if err == nil {
err = json.Unmarshal(data, token)
}
if f.ErrorHandler != nil {
f.ErrorHandler(err)
}
return
// Token returns the initial token read from the cache. It should be used to
// warm the authorization mechanism, token refreshes and later writes don't
// change the returned value. If no token is cached before, returns nil.
func (f *FileCache) Token() (token *Token) {
return f.initialToken
}
// Write writes a token to the specified file.