github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/cmd/jsjob/config.go (about) 1 package main 2 3 import ( 4 "os" 5 "strings" 6 "time" 7 8 "github.com/angenalZZZ/gofunc/configfile" 9 "github.com/angenalZZZ/gofunc/data" 10 "github.com/angenalZZZ/gofunc/data/cache/store" 11 "github.com/angenalZZZ/gofunc/f" 12 "github.com/angenalZZZ/gofunc/log" 13 nat "github.com/angenalZZZ/gofunc/rpc/nats" 14 "github.com/go-redis/redis/v7" 15 16 _ "github.com/denisenkom/go-mssqldb" 17 _ "github.com/go-sql-driver/mysql" 18 _ "github.com/mattn/go-sqlite3" 19 ) 20 21 var ( 22 configInfo *Config 23 configFile = "jsjob.yaml" 24 configMod time.Time 25 scriptFile string 26 scriptMod time.Time 27 ) 28 29 // Config The Config Info For jsjob.yaml 30 type Config struct { 31 Db struct { 32 Type string 33 Conn string 34 } 35 Cron string 36 Script string 37 Nats *nat.Connection 38 Redis *redis.Options 39 Log *log.Config 40 } 41 42 func initConfig() error { 43 isConfig := configInfo != nil 44 if !isConfig { 45 configInfo = new(Config) 46 } 47 48 if !isConfig && isConfigMod() == false { 49 return os.ErrNotExist 50 } 51 52 if err := configfile.YamlTo(configFile, configInfo); err != nil { 53 return err 54 } 55 56 if filename := configInfo.Cron; strings.HasSuffix(filename, ".js") { 57 scriptFile = filename 58 59 if !isConfig && isScriptMod() == false { 60 return os.ErrNotExist 61 } 62 63 if err := doScriptMod(); err != nil { 64 return err 65 } 66 } else { 67 configInfo.Cron = strings.TrimSpace(filename) 68 } 69 70 data.DbType, data.DbConn = configInfo.Db.Type, configInfo.Db.Conn 71 72 if store.RedisClient == nil && configInfo.Redis != nil && configInfo.Redis.Addr != "" { 73 store.RedisClient = redis.NewClient(configInfo.Redis) 74 } 75 76 return nil 77 } 78 79 func isConfigMod() bool { 80 if configFile == "" { 81 return false 82 } 83 info, err := os.Stat(configFile) 84 if os.IsNotExist(err) { 85 return false 86 } 87 if t := info.ModTime(); t.Unix() != configMod.Unix() { 88 configMod = t 89 return true 90 } 91 return false 92 } 93 94 func isScriptMod() bool { 95 if scriptFile == "" { 96 return false 97 } 98 info, err := os.Stat(scriptFile) 99 if os.IsNotExist(err) { 100 return false 101 } 102 if t := info.ModTime(); t.Unix() != scriptMod.Unix() { 103 scriptMod = t 104 return true 105 } 106 return false 107 } 108 109 func doScriptMod() error { 110 script, err := f.ReadFile(scriptFile) 111 if err != nil { 112 return err 113 } 114 115 configInfo.Script = strings.TrimSpace(string(script)) 116 return nil 117 }