forked from remote/oauth2
Cache read operation should be handled during construction.
This commit is contained in:
41
cache.go
41
cache.go
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user