oauth2/cache.go

61 lines
1.4 KiB
Go
Raw Normal View History

2014-05-21 09:55:21 -04:00
// Copyright 2014 The oauth2 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package oauth2
import (
"encoding/json"
"io/ioutil"
"os"
)
// 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)
// Write writes a token to the cache.
Write(token *Token)
}
// NewFileCache creates a new file cache.
func NewFileCache(filename string) (cache *FileCache) {
return &FileCache{filename: filename}
}
// 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
}
// Read reads the token from the cache file. If there exists no cache
// file, it returns nil for the token.
func (f *FileCache) Read() (token *Token, err error) {
data, err := ioutil.ReadFile(f.filename)
if os.IsNotExist(err) {
// no token has cached before, skip reading
return nil, nil
}
if err != nil {
return
}
if err = json.Unmarshal(data, &token); err != nil {
return
}
return
}
// Write writes a token to the specified file.
func (f *FileCache) Write(token *Token) {
data, err := json.Marshal(token)
if err == nil {
err = ioutil.WriteFile(f.filename, data, 0644)
}
2014-05-22 08:33:36 -04:00
if f.ErrorHandler != nil {
f.ErrorHandler(err)
}
}