2023-06-19 16:19:24 +09:00
|
|
|
package gocommon
|
2023-05-24 15:10:15 +09:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"os"
|
2024-02-04 21:03:48 +09:00
|
|
|
"path"
|
|
|
|
|
"strings"
|
2023-05-24 15:10:15 +09:00
|
|
|
"time"
|
2023-06-21 14:13:30 +09:00
|
|
|
|
|
|
|
|
"repositories.action2quare.com/ayo/gocommon/flagx"
|
2023-05-24 15:10:15 +09:00
|
|
|
)
|
|
|
|
|
|
2023-06-21 14:13:30 +09:00
|
|
|
var configfileflag = flagx.String("config", "", "")
|
|
|
|
|
|
2023-05-24 15:10:15 +09:00
|
|
|
func configFilePath() string {
|
2023-06-14 18:15:57 +09:00
|
|
|
configfilepath := "config.json"
|
2023-05-24 15:10:15 +09:00
|
|
|
if configfileflag != nil && len(*configfileflag) > 0 {
|
|
|
|
|
configfilepath = *configfileflag
|
|
|
|
|
}
|
|
|
|
|
|
2024-02-04 21:03:48 +09:00
|
|
|
if !strings.HasPrefix(configfilepath, "/") {
|
|
|
|
|
exe, _ := os.Executable()
|
|
|
|
|
configfilepath = path.Join(path.Dir(exe), configfilepath)
|
|
|
|
|
}
|
|
|
|
|
|
2023-05-24 15:10:15 +09:00
|
|
|
return configfilepath
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func ConfigModTime() time.Time {
|
|
|
|
|
fi, err := os.Stat(configFilePath())
|
|
|
|
|
if err == nil {
|
|
|
|
|
return fi.ModTime()
|
|
|
|
|
}
|
|
|
|
|
return time.Time{}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func MonitorConfig[T any](onChanged func(newconf *T)) error {
|
|
|
|
|
fi, err := os.Stat(configFilePath())
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
go func(modTime time.Time, filepath string) {
|
|
|
|
|
for {
|
|
|
|
|
if fi, err := os.Stat(filepath); err == nil {
|
|
|
|
|
if modTime != fi.ModTime() {
|
|
|
|
|
var next T
|
|
|
|
|
if err := LoadConfig(&next); err == nil {
|
|
|
|
|
fi, _ := os.Stat(filepath)
|
|
|
|
|
modTime = fi.ModTime()
|
|
|
|
|
|
|
|
|
|
onChanged(&next)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
time.Sleep(time.Second)
|
|
|
|
|
}
|
|
|
|
|
}(fi.ModTime(), configFilePath())
|
|
|
|
|
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func LoadConfig[T any](outptr *T) error {
|
|
|
|
|
configfilepath := configFilePath()
|
|
|
|
|
content, err := os.ReadFile(configfilepath)
|
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
|
return os.WriteFile(configfilepath, []byte("{}"), 0666)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return json.Unmarshal(content, outptr)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type StorageAddr struct {
|
|
|
|
|
Mongo string
|
2023-07-19 09:35:25 +09:00
|
|
|
Redis map[string]string
|
2023-05-24 15:10:15 +09:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type RegionStorageConfig struct {
|
|
|
|
|
RegionStorage map[string]StorageAddr `json:"region_storage"`
|
|
|
|
|
}
|