This repository has been archived on 2026-03-28. You can view files and clone it, but cannot push or open issues or pull requests.
old-sysmonitord/internal/config/loader.go
2026-03-22 12:16:48 +08:00

56 lines
1.2 KiB
Go

package config
import (
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
type RemoteConfigLoader struct {
client *http.Client
}
func NewRemoteConfigLoader() *RemoteConfigLoader {
return &RemoteConfigLoader{
client: &http.Client{Timeout: 10 * time.Second},
}
}
func (l *RemoteConfigLoader) LoadConfigs(OfficialURL, UserURL string) (*OfficialConfig, *UserConfig, error) {
var officialCfg OfficialConfig
var userCfg UserConfig
// 加载官方配置
if err := l.fetchJSON(OfficialURL, &officialCfg); err != nil {
return nil, nil, fmt.Errorf("[致命错误]加载官方配置失败: %v", err)
}
// 加载用户配置
if err := l.fetchJSON(UserURL, &userCfg); err != nil {
return nil, nil, fmt.Errorf("[致命错误]加载用户配置失败: %v", err)
}
return &officialCfg, &userCfg, nil
}
func (l *RemoteConfigLoader) fetchJSON(url string, target interface{}) error {
resp, err := l.client.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("请求失败: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
return json.Unmarshal(body, target)
}