document WithCache function

This commit is contained in:
c9s 2020-10-20 12:22:18 +08:00
parent 2bbee6671a
commit 752fdf5c80

View File

@ -10,12 +10,19 @@ import (
"github.com/pkg/errors"
)
func WithCache(key string, obj interface{}, do func() (interface{}, error)) error {
type DataFetcher func() (interface{}, error)
// WithCache let you use the cache with the given cache key, variable reference and your data fetcher,
// The key must be an unique ID.
// obj is the pointer of your local variable
// fetcher is the closure that will fetch your remote data or some slow operation.
func WithCache(key string, obj interface{}, fetcher DataFetcher) error {
cacheDir := CacheDir()
cacheFile := path.Join(cacheDir, key+ ".json")
if _, err := os.Stat(cacheFile); os.IsNotExist(err) {
data, err := do()
data, err := fetcher()
if err != nil {
return err
}