global.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package global
  2. import (
  3. "eta/mysteel_watch/config"
  4. "eta/mysteel_watch/utils"
  5. "fmt"
  6. "github.com/fsnotify/fsnotify"
  7. oplogging "github.com/op/go-logging"
  8. "github.com/patrickmn/go-cache"
  9. "github.com/spf13/viper"
  10. "io/fs"
  11. "os"
  12. "path/filepath"
  13. "syscall"
  14. "time"
  15. )
  16. var (
  17. CONFIG config.Config //配置文件
  18. LOG *oplogging.Logger
  19. CacheClient *cache.Cache
  20. )
  21. const ConfigFile = "config/config.yaml" //本地(测试)环境下的配置文件地址
  22. const ProConfigFile = "config/config.yaml" //生产环境下的配置文件地址
  23. func init() {
  24. v := viper.New()
  25. configFilePath := ConfigFile
  26. //如果不存在该配置文件,那么应该是线上环境,那么去寻找线上配置文件的路径
  27. if !utils.FileIsExist(configFilePath) {
  28. configFilePath = ProConfigFile
  29. }
  30. fmt.Println("configFilePath->", configFilePath)
  31. //设置配置文件
  32. v.SetConfigFile(configFilePath)
  33. err := v.ReadInConfig()
  34. if err != nil {
  35. panic(fmt.Errorf("读取配置失败,Err: %s \n", err))
  36. }
  37. //持续监听文件
  38. v.WatchConfig()
  39. v.OnConfigChange(func(e fsnotify.Event) {
  40. fmt.Println("配置文件变更:", e.Name)
  41. if err := v.Unmarshal(&CONFIG); err != nil {
  42. fmt.Println("配置重赋值失败,Err:", err)
  43. }
  44. fmt.Println(CONFIG)
  45. })
  46. if err := v.Unmarshal(&CONFIG); err != nil {
  47. fmt.Println("配置初始化赋值失败,Err:", err)
  48. }
  49. CacheClient = cache.New(365*24*time.Hour, 365*24*time.Hour)
  50. ReadDefaultFileModifyTime()
  51. }
  52. func ReadDefaultFileModifyTime() {
  53. cacheClient := CacheClient
  54. if cacheClient == nil {
  55. cacheClient = cache.New(365*24*time.Hour, 365*24*time.Hour)
  56. }
  57. err := filepath.Walk(CONFIG.Serve.IndexSaveDir, func(path string, info fs.FileInfo, err error) error {
  58. if err != nil {
  59. return err
  60. }
  61. if !info.IsDir() {
  62. fmt.Println(path)
  63. fileInfo, err := os.Stat(path)
  64. if err != nil {
  65. fmt.Println("os.Stat:", err.Error())
  66. }
  67. winFileAttr := fileInfo.Sys().(*syscall.Win32FileAttributeData)
  68. modifyTime := SecondToTime(winFileAttr.LastWriteTime.Nanoseconds() / 1e9).Format(utils.FormatDateTime)
  69. fmt.Println("最后修改时间:", modifyTime)
  70. cacheClient.Set(path, modifyTime, 24*time.Hour)
  71. }
  72. return nil
  73. })
  74. fmt.Println("Read err:", err)
  75. }
  76. // 把秒级的时间戳转为time格式
  77. func SecondToTime(sec int64) time.Time {
  78. return time.Unix(sec, 0)
  79. }