github.com/gogf/gf@v1.16.9/os/gfile/gfile_cache.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package gfile 8 9 import ( 10 "github.com/gogf/gf/os/gcache" 11 "github.com/gogf/gf/os/gcmd" 12 "github.com/gogf/gf/os/gfsnotify" 13 "time" 14 ) 15 16 const ( 17 defaultCacheExpire = time.Minute // defaultCacheExpire is the expire time for file content caching in seconds. 18 commandEnvKeyForCache = "gf.gfile.cache" // commandEnvKeyForCache is the configuration key for command argument or environment configuring cache expire duration. 19 ) 20 21 var ( 22 // Default expire time for file content caching. 23 cacheExpire = gcmd.GetOptWithEnv(commandEnvKeyForCache, defaultCacheExpire).Duration() 24 25 // internalCache is the memory cache for internal usage. 26 internalCache = gcache.New() 27 ) 28 29 // GetContentsWithCache returns string content of given file by <path> from cache. 30 // If there's no content in the cache, it will read it from disk file specified by <path>. 31 // The parameter <expire> specifies the caching time for this file content in seconds. 32 func GetContentsWithCache(path string, duration ...time.Duration) string { 33 return string(GetBytesWithCache(path, duration...)) 34 } 35 36 // GetBytesWithCache returns []byte content of given file by <path> from cache. 37 // If there's no content in the cache, it will read it from disk file specified by <path>. 38 // The parameter <expire> specifies the caching time for this file content in seconds. 39 func GetBytesWithCache(path string, duration ...time.Duration) []byte { 40 key := cacheKey(path) 41 expire := cacheExpire 42 if len(duration) > 0 { 43 expire = duration[0] 44 } 45 r, _ := internalCache.GetOrSetFuncLock(key, func() (interface{}, error) { 46 b := GetBytes(path) 47 if b != nil { 48 // Adding this <path> to gfsnotify, 49 // it will clear its cache if there's any changes of the file. 50 _, _ = gfsnotify.Add(path, func(event *gfsnotify.Event) { 51 internalCache.Remove(key) 52 gfsnotify.Exit() 53 }) 54 } 55 return b, nil 56 }, expire) 57 if r != nil { 58 return r.([]byte) 59 } 60 return nil 61 } 62 63 // cacheKey produces the cache key for gcache. 64 func cacheKey(path string) string { 65 return commandEnvKeyForCache + path 66 }