diff --git a/g/os/gfcache/gfcache.go b/g/os/gfcache/gfcache.go index 9cea2062b..d32bb1f18 100644 --- a/g/os/gfcache/gfcache.go +++ b/g/os/gfcache/gfcache.go @@ -8,6 +8,8 @@ package gfcache import ( + "time" + "github.com/gogf/gf/g/internal/cmdenv" "github.com/gogf/gf/g/os/gcache" "github.com/gogf/gf/g/os/gfile" @@ -27,18 +29,18 @@ var ( // GetContents returns string content of given file by from cache. // If there's no content in the cache, it will read it from disk file specified by . // The parameter specifies the caching time for this file content in seconds. -func GetContents(path string, expire ...int) string { - return string(GetBinContents(path, expire...)) +func GetContents(path string, duration ...interface{}) string { + return string(GetBinContents(path, duration...)) } // GetBinContents returns []byte content of given file by from cache. // If there's no content in the cache, it will read it from disk file specified by . // The parameter specifies the caching time for this file content in seconds. -func GetBinContents(path string, expire ...int) []byte { +func GetBinContents(path string, duration ...interface{}) []byte { k := cacheKey(path) e := cacheExpire - if len(expire) > 0 { - e = expire[0] + if len(duration) > 0 { + e = getSecondExpire(duration[0]) } r := gcache.GetOrSetFuncLock(k, func() interface{} { b := gfile.GetBinContents(path) @@ -58,7 +60,18 @@ func GetBinContents(path string, expire ...int) []byte { return nil } -// 生成缓存键名 +// getSecondExpire converts parameter to int type in seconds. +// +// Note that there's some performance cost in type assertion here, but it's valuable. +func getSecondExpire(duration interface{}) int { + if d, ok := duration.(time.Duration); ok { + return int(d.Nanoseconds() / 1000000000) + } else { + return duration.(int) + } +} + +// cacheKey produces the cache key for gcache. func cacheKey(path string) string { return "gf.gfcache:" + path }