-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.go
More file actions
80 lines (63 loc) · 2.01 KB
/
Copy pathconfig.go
File metadata and controls
80 lines (63 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package plugin_config
import (
"fmt"
"github.com/spf13/viper"
"github.com/yeswearebot/yes-core/core"
)
// ConfigPlugin 它既是一个 core.Plugin,同时对外暴露配置读取能力
type ConfigPlugin struct {
viper *viper.Viper
}
func init() {
core.Register(func() core.Plugin { return &ConfigPlugin{} })
}
func (c *ConfigPlugin) Name() string { return "config" }
func (c *ConfigPlugin) Init(ctx *core.SystemContext) error {
v := viper.New()
v.SetConfigName("config")
v.SetConfigType("yaml")
v.AddConfigPath(".")
v.AddConfigPath("./examples/config_usage") // 兼容测试目录
if err := v.ReadInConfig(); err != nil {
return fmt.Errorf("fatal error config file: %w", err)
}
c.viper = v
fmt.Println("[Config] 配置文件加载完毕,服务已就绪")
return nil
}
// Unmarshal 让用户插件极其方便地将配置绑定到自己的结构体
func (c *ConfigPlugin) Unmarshal(key string, val any) error {
return c.viper.UnmarshalKey(key, val)
}
// GetString 提供快捷获取基础类型的方法
func (c *ConfigPlugin) GetString(key string) string {
return c.viper.GetString(key)
}
func (c *ConfigPlugin) Start(ctx *core.SystemContext) error { return nil }
func (c *ConfigPlugin) Stop(ctx *core.SystemContext) error { return nil }
// Unmarshal 全局快捷方法。
// 用法: plugin_config.Unmarshal(ctx, "bot", &myCfg)
func Unmarshal(ctx *core.SystemContext, key string, val any) error {
rawPlugin, ok := ctx.Registry.Get("config")
if !ok {
return fmt.Errorf("config plugin not found, please ensure plugin_config is imported")
}
cfgPlugin, ok := rawPlugin.(*ConfigPlugin)
if !ok {
return fmt.Errorf("config plugin type assertion failed")
}
return cfgPlugin.Unmarshal(key, val)
}
// GetString 全局快捷方法。
// 用法: plugin_config.GetString(ctx, "bot.name")
func GetString(ctx *core.SystemContext, key string) string {
rawPlugin, ok := ctx.Registry.Get("config")
if !ok {
return ""
}
cfgPlugin, ok := rawPlugin.(*ConfigPlugin)
if !ok {
return ""
}
return cfgPlugin.GetString(key)
}