|
| 1 | +package Common |
| 2 | + |
| 3 | +import ( |
| 4 | + "crypto/md5" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "github.com/fsnotify/fsnotify" |
| 8 | + "log" |
| 9 | + "os" |
| 10 | + "os/exec" |
| 11 | + "path/filepath" |
| 12 | + "strconv" |
| 13 | + "strings" |
| 14 | +) |
| 15 | + |
| 16 | +func InitConfig() (err error) { |
| 17 | + runPath, err := GetCurrentPath() |
| 18 | + |
| 19 | + Config.SetConfigType("json") |
| 20 | + |
| 21 | + Config.SetConfigName("config") |
| 22 | + Config.AddConfigPath(runPath) |
| 23 | + err = Config.ReadInConfig() |
| 24 | + |
| 25 | + if err != nil { // Handle errors reading the config file |
| 26 | + log.Println(runPath) |
| 27 | + return errors.New(fmt.Sprintf("Fatal error config file: %s \n", err)) |
| 28 | + } |
| 29 | + |
| 30 | + Config.WatchConfig() |
| 31 | + Config.OnConfigChange(func(in fsnotify.Event) { |
| 32 | + log.Println(os.Getpid(), "Config file changed:", in.Name, in.Op.String()) |
| 33 | + err = Config.ReadInConfig() |
| 34 | + |
| 35 | + if err != nil { // Handle errors reading the config file |
| 36 | + log.Println(os.Getpid(), fmt.Errorf("Fatal error config file: %s \n", err)) |
| 37 | + } else { |
| 38 | + log.Println(os.Getpid(), "reload config success") |
| 39 | + } |
| 40 | + }) |
| 41 | + return |
| 42 | +} |
| 43 | + |
| 44 | +func GetCurrentPath() (string, error) { |
| 45 | + file, err := exec.LookPath(os.Args[0]) |
| 46 | + //if err != nil { |
| 47 | + // return "", err |
| 48 | + //} |
| 49 | + path, err := filepath.Abs(file) |
| 50 | + if err != nil { |
| 51 | + return "", err |
| 52 | + } |
| 53 | + |
| 54 | + i := strings.LastIndex(path, "/") |
| 55 | + if i < 0 { |
| 56 | + i = strings.LastIndex(path, "\\") |
| 57 | + } |
| 58 | + |
| 59 | + if i < 0 { |
| 60 | + return "", errors.New(`error: Can't find "/" or "\".`) |
| 61 | + } |
| 62 | + return string(path[0 : i+1]), nil |
| 63 | +} |
| 64 | + |
| 65 | +func FastAtoi(num string) int { |
| 66 | + ret, _ := strconv.Atoi(num) |
| 67 | + return ret |
| 68 | +} |
| 69 | + |
| 70 | +func FastJsonMarshal(_json interface{}) string { |
| 71 | + str, _ := Json.MarshalToString(_json) |
| 72 | + return str |
| 73 | +} |
| 74 | + |
| 75 | +func Md5(str string) string { |
| 76 | + data := []byte(str) |
| 77 | + has := md5.Sum(data) |
| 78 | + md5str := fmt.Sprintf("%x", has) |
| 79 | + return md5str |
| 80 | +} |
| 81 | + |
| 82 | +func SafeGetError(err error) string { |
| 83 | + if nil == err { |
| 84 | + return "" |
| 85 | + } else { |
| 86 | + return err.Error() |
| 87 | + } |
| 88 | +} |
0 commit comments