配置读取功能实现,核心功能未实现
This commit is contained in:
74
pkg/conf/conf.go
Normal file
74
pkg/conf/conf.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"NaiveBotRouter/pkg/log"
|
||||
"NaiveBotRouter/pkg/util"
|
||||
"encoding/json"
|
||||
"github.com/BurntSushi/toml"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Common Common
|
||||
Servers map[string]Server
|
||||
}
|
||||
|
||||
type Common struct {
|
||||
Name string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Addr string
|
||||
}
|
||||
|
||||
var (
|
||||
GlobalConfig Config
|
||||
BackendConfig Server
|
||||
)
|
||||
|
||||
// 释放默认配置文件
|
||||
func releaseConfig(file string, config Config) {
|
||||
f, err := util.CreateNestedFile(file)
|
||||
if err != nil {
|
||||
log.Log.Fatalf("failed to create default config: %s", err.Error())
|
||||
}
|
||||
|
||||
encoder := toml.NewEncoder(f)
|
||||
err = encoder.Encode(config)
|
||||
if err != nil {
|
||||
log.Log.Fatalf("internal - encoding toml: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func InitConfig(file string) {
|
||||
GlobalConfig = defaultConfig
|
||||
|
||||
if util.NotExists(file) {
|
||||
// 默认配置文件不存在则创建
|
||||
if file == "config.toml" {
|
||||
releaseConfig(file, GlobalConfig)
|
||||
log.Log.Infof("default config created")
|
||||
} else {
|
||||
log.Log.Fatalf("config file not exists: %s", file)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
// 解析配置文件
|
||||
_, err := toml.DecodeFile(file, &GlobalConfig)
|
||||
if err != nil {
|
||||
log.Log.Fatalf("toml decoding error: %s", err.Error())
|
||||
}
|
||||
|
||||
// 验证必须的字段
|
||||
if v, ok := GlobalConfig.Servers["backend"]; ok {
|
||||
BackendConfig = v
|
||||
} else {
|
||||
log.Log.Fatalf("mission required field: servers.backend")
|
||||
}
|
||||
|
||||
jsonConfig, err := json.Marshal(GlobalConfig)
|
||||
if err == nil {
|
||||
log.Log.Debugf("config loaded: %s", string(jsonConfig))
|
||||
}
|
||||
}
|
||||
7
pkg/conf/conf_test.go
Normal file
7
pkg/conf/conf_test.go
Normal file
@@ -0,0 +1,7 @@
|
||||
package conf
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestInitConfig(t *testing.T) {
|
||||
InitConfig("fconfig.toml")
|
||||
}
|
||||
15
pkg/conf/default.go
Normal file
15
pkg/conf/default.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package conf
|
||||
|
||||
var defaultConfig Config
|
||||
|
||||
func init() {
|
||||
defaultConfig = Config{
|
||||
Common: Common{
|
||||
Name: "NaiveBotRouter",
|
||||
},
|
||||
Servers: map[string]Server{
|
||||
"backend": {Addr: "127.0.0.1:5700/ws"},
|
||||
"frontend1": {Addr: "127.0.0.1:6600/onebot/v11/ws"},
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user