gfile_cache.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2017-2018 gf Author(https://github.com/gogf/gf). 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. package gfile
  7. import (
  8. "github.com/gogf/gf/os/gcache"
  9. "github.com/gogf/gf/os/gcmd"
  10. "github.com/gogf/gf/os/gfsnotify"
  11. "time"
  12. )
  13. const (
  14. // Default expire time for file content caching in seconds.
  15. gDEFAULT_CACHE_EXPIRE = time.Minute
  16. )
  17. var (
  18. // Default expire time for file content caching.
  19. cacheExpire = gcmd.GetWithEnv("gf.gfile.cache", gDEFAULT_CACHE_EXPIRE).Duration()
  20. // internalCache is the memory cache for internal usage.
  21. internalCache = gcache.New()
  22. )
  23. // GetContents returns string content of given file by <path> from cache.
  24. // If there's no content in the cache, it will read it from disk file specified by <path>.
  25. // The parameter <expire> specifies the caching time for this file content in seconds.
  26. func GetContentsWithCache(path string, duration ...time.Duration) string {
  27. return string(GetBytesWithCache(path, duration...))
  28. }
  29. // GetBinContents returns []byte 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 GetBytesWithCache(path string, duration ...time.Duration) []byte {
  33. key := cacheKey(path)
  34. expire := cacheExpire
  35. if len(duration) > 0 {
  36. expire = duration[0]
  37. }
  38. r, _ := internalCache.GetOrSetFuncLock(key, func() (interface{}, error) {
  39. b := GetBytes(path)
  40. if b != nil {
  41. // Adding this <path> to gfsnotify,
  42. // it will clear its cache if there's any changes of the file.
  43. _, _ = gfsnotify.Add(path, func(event *gfsnotify.Event) {
  44. internalCache.Remove(key)
  45. gfsnotify.Exit()
  46. })
  47. }
  48. return b, nil
  49. }, expire)
  50. if r != nil {
  51. return r.([]byte)
  52. }
  53. return nil
  54. }
  55. // cacheKey produces the cache key for gcache.
  56. func cacheKey(path string) string {
  57. return "gf.gfile.cache:" + path
  58. }