重构配置加载方式并引入sync.Once确保单例

将配置加载逻辑从全局变量改为使用sync.Once确保单例模式,
优化了config包的结构,现在通过GetConfig方法来获取配置,
而不是直接访问全局变量。这种方式更加线程安全,并且
允许未来在不同包中异步加载配置而无需担心初始化顺序问题。

BREAKING CHANGE: 现在必须使用config.GetConfig()来获取配置,
而不是直接访问config.GlobalConfig。这可能需要更新任何
依赖于GlobalConfig的代码。
This commit is contained in:
liyp 2024-06-30 16:12:26 +08:00
parent 383cdf1e02
commit cdb74588b2
3 changed files with 32 additions and 31 deletions

View file

@ -1,35 +1,24 @@
package config
import (
"log"
"sync"
"github.com/BurntSushi/toml"
)
type Config struct {
Server struct {
APIURL string
POSTURL string
}
Group struct {
AllowGroup []string
AllowUser []string
AllowRole []string
BlockGroup []string
BlockUser []string
GroupNotAllow []string
UserNotAllow []string
RoleNotAllow []string
}
}
var (
config map[string]interface{}
once sync.Once
)
var GlobalConfig Config
func loadConfig() {
func init() {
// var config Config
if _, err := toml.DecodeFile("config.toml", &GlobalConfig); err != nil {
println("配置文件不正确,请修改正确的配置文件!")
log.Fatal(err)
if _, err := toml.DecodeFile("config.toml", &config); err != nil {
panic(err)
}
// fmt.Println(config.Group)
}
func GetConfig() map[string]interface{} {
once.Do(loadConfig)
return config
}

View file

@ -114,7 +114,13 @@ func handlePost(w http.ResponseWriter, r *http.Request) {
}
func main() {
APIURL := config.GlobalConfig.Server.APIURL
// var config map[string]interface{}
// if _, err := toml.DecodeFile("config.toml", &config); err != nil {
// println("配置文件不正确,请修改正确的配置文件!")
// log.Fatal(err)
// }
cfg := config.GetConfig()
APIURL := cfg["APIURL"].(string)
// PORT := config.GlobalConfig.Server.Port
// fmt.Println(APIURL)

View file

@ -25,7 +25,13 @@ type StdAns struct {
RawMsg string
}
var cfg map[string]interface{}
func init() {
cfg = config.GetConfig()
}
func NewStdAns(parms []string, uid, gid, role, mid, rawMsg string) *StdAns {
return &StdAns{
Parms: parms,
UID: uid,
@ -33,11 +39,11 @@ func NewStdAns(parms []string, uid, gid, role, mid, rawMsg string) *StdAns {
Role: role,
MID: mid,
RawMsg: rawMsg,
AllowGroup: config.GlobalConfig.Group.AllowGroup,
AllowUser: config.GlobalConfig.Group.AllowUser,
AllowRole: config.GlobalConfig.Group.AllowRole,
BlockGroup: config.GlobalConfig.Group.BlockGroup,
BlockUser: config.GlobalConfig.Group.BlockUser,
AllowGroup: cfg["AllowGroup"].([]string),
AllowUser: cfg["AllowUser"].([]string),
AllowRole: cfg["AllowRole"].([]string),
BlockGroup: cfg["BlockGroup"].([]string),
BlockUser: cfg["BlockUser"].([]string),
GroupNotAllow: "汝所在的群组不被允许这样命令咱呢.",
UserNotAllow: "汝不被允许呢.",
RoleNotAllow: "汝的角色不被允许哦.",
@ -99,7 +105,7 @@ func (s *StdAns) SendMsg(msg string) bool {
}
// fmt.Println(string(re))
url := config.GlobalConfig.Server.POSTURL
url := cfg["POSTURL"].(string)
// println("core:", url)
// fmt.Println("请求地址:", url)
fmt.Println("响应信息:\n", msg)