专为
yes-core打造的配置中心插件。
go get github.com/yeswearebot/plugin_config在 Go 中,struct 配合 mapstructure 标签,就等同于 TypeScript 里的 interface:
// 类似 TS: interface BotConfig { name: string, version: string, superusers: string[] }
type BotConfig struct {
Name string `mapstructure:"name"`
Version string `mapstructure:"version"`
Superusers []string `mapstructure:"superusers"`
}在项目根目录创建 config.yaml:
bot:
name: "Yesimbot"
version: "1.0.0"
superusers:
- "123456"在你的插件 Init 或 Start 生命周期中,直接调用 plugin_config.Unmarshal:
package my_plugin
import (
"fmt"
"github.com/yeswearebot/yes-core/core"
"github.com/yeswearebot/plugin_config" // 引入配置服务
)
type BotConfig struct {
Name string `mapstructure:"name"`
Version string `mapstructure:"version"`
Superusers []string `mapstructure:"superusers"`
}
type MyPlugin struct{}
func init() {
core.Register(func() core.Plugin { return &MyPlugin{} })
}
func (p *MyPlugin) Name() string { return "my-plugin" }
func (p *MyPlugin) DependsOn() []string { return []string{"config"} } // 声明配置服务依赖
func (p *MyPlugin) Start(ctx *core.SystemContext) error { return nil }
func (p *MyPlugin) Stop(ctx *core.SystemContext) error { return nil }
func (p *MyPlugin) Init(ctx *core.SystemContext) error {
// 实例化你的配置结构体
var cfg BotConfig
// 一行代码搞定配置读取!
if err := plugin_config.Unmarshal(ctx, "bot", &cfg); err != nil {
return err
}
// 现在你可以像在 TS 里一样愉快地使用强类型配置了
fmt.Printf("Bot Name: %s\n", cfg.Name)
fmt.Printf("Superusers: %v\n", cfg.Superusers)
return nil
}别忘了在 main.go 中用下划线引入它:
package main
import (
"github.com/yeswearebot/yes-core/core"
_ "github.com/yeswearebot/plugin_config"
)
func main() {
app := core.NewApp()
app.Run()
}为了帮助你更好地理解,这里有一份对照表:
| Koishi (TS) | yes-core (Go) | 说明 |
|---|---|---|
interface Config |
struct Config + mapstructure |
定义配置结构 |
ctx.config |
plugin_config.Unmarshal(ctx, ...) |
获取并解析配置 |
apply(ctx) |
Init(ctx) |
插件注册入口 |
Schema.intersect(...) |
暂无 | Go 强类型在编译期已保证类型安全,无需运行时校验 |