From defeac306ac8341b795edb2d9f0826a88f082587 Mon Sep 17 00:00:00 2001 From: kercylan98 Date: Fri, 19 May 2023 13:47:49 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=BC=E5=AE=B9=E9=85=8D=E7=BD=AE=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E5=B7=A5=E5=85=B7=E7=9A=84=E5=8A=A0=E8=BD=BD=E5=AE=9E?= =?UTF-8?q?=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/config.go | 78 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 config/config.go diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..f071259 --- /dev/null +++ b/config/config.go @@ -0,0 +1,78 @@ +package config + +import ( + jsonIter "github.com/json-iterator/go" + "github.com/kercylan98/minotaur/utils/log" + "github.com/kercylan98/minotaur/utils/timer" + "go.uber.org/zap" + "os" + "path/filepath" + "sync" + "time" +) + +type LoadHandle func(handle func(filename string, config any) error) +type RefreshHandle func() + +const ( + tickerLoadRefresh = "_tickerLoadRefresh" +) + +var ( + cLoadDir string + cTicker *timer.Ticker + cInterval time.Duration + cLoadHandle LoadHandle + cRefreshHandle RefreshHandle + json = jsonIter.ConfigCompatibleWithStandardLibrary + mutex sync.Mutex +) + +func Init(loadDir string, loadHandle LoadHandle, refreshHandle RefreshHandle) { + cLoadDir = loadDir + cLoadHandle = loadHandle + cRefreshHandle = refreshHandle +} + +func Load() { + mutex.Lock() + if cTicker != nil { + WithTickerLoad(cTicker, cInterval) + } else { + cLoadHandle(func(filename string, config any) error { + bytes, err := os.ReadFile(filepath.Join(cLoadDir, filename)) + if err != nil { + return err + } + if err = json.Unmarshal(bytes, &config); err == nil { + log.Error("Config", zap.String("Name", filename), zap.Bool("LoadSuccess", true)) + } + return err + }) + } + mutex.Unlock() +} + +func WithTickerLoad(ticker *timer.Ticker, interval time.Duration) { + if ticker != cTicker && cTicker != nil { + cTicker.StopTimer(tickerLoadRefresh) + } + cTicker = ticker + cInterval = interval + cTicker.Loop(tickerLoadRefresh, timer.Instantly, cInterval, timer.Forever, func() { + Load() + Refresh() + }) +} + +func StopTickerLoad() { + if cTicker != nil { + cTicker.StopTimer(tickerLoadRefresh) + } +} + +func Refresh() { + mutex.Lock() + cRefreshHandle() + mutex.Unlock() +}