go-ayo/common을 gocommon으로 분리
This commit is contained in:
75
reflect_config.go
Normal file
75
reflect_config.go
Normal file
@ -0,0 +1,75 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
var configfileflag = flag.String("config", "", "")
|
||||
|
||||
func configFilePath() string {
|
||||
configfilepath := "./config_template.json"
|
||||
if configfileflag != nil && len(*configfileflag) > 0 {
|
||||
configfilepath = *configfileflag
|
||||
}
|
||||
|
||||
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
|
||||
Redis struct {
|
||||
URL string
|
||||
Offset map[string]int
|
||||
}
|
||||
}
|
||||
|
||||
type RegionStorageConfig struct {
|
||||
RegionStorage map[string]StorageAddr `json:"region_storage"`
|
||||
}
|
||||
Reference in New Issue
Block a user