feat: add formiliy support

This commit is contained in:
langhuihui
2023-12-01 17:54:10 +08:00
parent 268b237e35
commit 9e2ca2a670
7 changed files with 614 additions and 400 deletions

108
plugin.go
View File

@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
@@ -52,7 +51,7 @@ func InstallPlugin(config config.Plugin) *Plugin {
return plugin
}
type FirstConfig config.Config
type FirstConfig *config.Config
type DefaultYaml string
// Plugin 插件信息
@@ -62,10 +61,7 @@ type Plugin struct {
Name string //插件名称
Config config.Plugin `json:"-" yaml:"-"` //类型化的插件配置
Version string //插件版本
Yaml string //配置文件中的配置项
modifiedYaml string //修改过的配置的yaml文件内容
RawConfig config.Config //最终合并后的配置的map形式方便查询
Modified config.Config //修改过的配置项
*log.Logger `json:"-" yaml:"-"`
saveTimer *time.Timer //用于保存的时候的延迟,防抖
Disabled bool
@@ -104,73 +100,20 @@ func (opt *Plugin) assign() {
f, err := os.Open(opt.settingPath())
defer f.Close()
if err == nil {
var b []byte
b, err = io.ReadAll(f)
if err == nil {
opt.modifiedYaml = string(b)
if err = yaml.Unmarshal(b, &opt.Modified); err == nil {
err = yaml.Unmarshal(b, &opt.RawConfig)
}
}
if err != nil {
opt.Warn("assign config failed", zap.Error(err))
}
}
if opt == Engine {
opt.registerHandler()
return
}
if EngineConfig.DisableAll {
opt.Disabled = true
}
if opt.RawConfig == nil {
opt.RawConfig = config.Config{}
} else if opt.RawConfig["enable"] == false {
opt.Disabled = true
} else if opt.RawConfig["enable"] == true {
opt.Disabled = false
//移除这个属性防止反序列化报错
delete(opt.RawConfig, "enable")
}
if opt.Disabled {
opt.Warn("plugin disabled")
return
}
t := reflect.TypeOf(opt.Config).Elem()
// 用全局配置覆盖没有设置的配置
for _, fname := range MergeConfigs {
if _, ok := t.FieldByName(fname); ok {
if v, ok := Engine.RawConfig[strings.ToLower(fname)]; ok {
if !opt.RawConfig.Has(fname) {
opt.RawConfig.Set(fname, v)
} else if opt.RawConfig.HasChild(fname) {
opt.RawConfig.GetChild(fname).Merge(Engine.RawConfig.GetChild(fname))
}
}
}
var modifyConfig map[string]any
err = yaml.NewDecoder(f).Decode(&modifyConfig)
opt.RawConfig.ParseModifyFile(modifyConfig)
}
opt.registerHandler()
opt.run()
if opt != Engine {
opt.run()
}
}
func (opt *Plugin) run() {
opt.Context, opt.CancelFunc = context.WithCancel(Engine)
opt.RawConfig.Unmarshal(opt.Config)
opt.RawConfig = config.Struct2Config(opt.Config, strings.ToUpper(opt.Name))
// var buffer bytes.Buffer
// err := yaml.NewEncoder(&buffer).Encode(opt.Config)
// if err != nil {
// panic(err)
// }
// err = yaml.NewDecoder(&buffer).Decode(&opt.RawConfig)
// if err != nil {
// panic(err)
// }
opt.Config.OnEvent(FirstConfig(opt.RawConfig))
delete(opt.RawConfig, "defaultyaml")
opt.Config.OnEvent(FirstConfig(&opt.RawConfig))
opt.Debug("config", zap.Any("config", opt.Config))
// opt.RawConfig = config.Struct2Config(opt.Config)
if conf, ok := opt.Config.(config.HTTPConfig); ok {
go conf.Listen(opt)
}
@@ -180,8 +123,7 @@ func (opt *Plugin) run() {
}
// Update 热更新配置
func (opt *Plugin) Update(conf config.Config) {
conf.Unmarshal(opt.Config)
func (opt *Plugin) Update(conf *config.Config) {
opt.Config.OnEvent(conf)
}
@@ -198,22 +140,6 @@ func (opt *Plugin) registerHandler() {
switch handler := v.Method(i).Interface().(type) {
case func(http.ResponseWriter, *http.Request):
opt.handle(patten, http.HandlerFunc(handler))
// case func(*http.Request) (int, string, any):
// opt.handle(patten, http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
// code, msg, data := handler(r)
// switch returnMode {
// case "json":
// rw.Header().Set("Content-Type", "application/json")
// rw.WriteHeader(http.StatusOK)
// json.NewEncoder(rw).Encode(map[string]interface{}{
// "code": code,
// "msg": msg,
// "data": data,
// })
// default:
// http.Error(rw, msg, code)
// }
// }))
}
}
}
@@ -231,7 +157,7 @@ func (opt *Plugin) Save() error {
file, err := os.OpenFile(opt.settingPath(), os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err == nil {
defer file.Close()
err = yaml.NewEncoder(file).Encode(opt.Modified)
err = yaml.NewEncoder(file).Encode(opt.RawConfig.Modify)
}
if err == nil {
opt.Info("config saved")
@@ -279,7 +205,7 @@ func (opt *Plugin) SubscribeExist(streamPath string, sub ISubscriber) error {
}
return opt.Subscribe(streamPath, sub)
}
func (opt *Plugin) AssignSubConfig(suber *Subscriber) {
func (opt *Plugin) AssignSubConfig(suber *Subscriber) {
if suber.Config == nil {
conf, ok := opt.Config.(config.SubscribeConfig)
if !ok {
@@ -292,6 +218,7 @@ func (opt *Plugin) AssignSubConfig(suber *Subscriber) {
suber.ID = fmt.Sprintf("%d", uintptr(unsafe.Pointer(suber)))
}
}
// Subscribe 订阅一个流,如果流不存在则创建一个等待流
func (opt *Plugin) Subscribe(streamPath string, sub ISubscriber) error {
suber := sub.GetSubscriber()
@@ -335,14 +262,12 @@ func (opt *Plugin) Pull(streamPath string, url string, puller IPuller, save int)
switch save {
case 1:
pullConf.AddPullOnStart(streamPath, url)
opt.RawConfig.Get("pull").Get("pullonstart").Modify = pullConf.PullOnStart
case 2:
pullConf.AddPullOnSub(streamPath, url)
opt.RawConfig.Get("pull").Get("pullonsub").Modify = pullConf.PullOnSub
}
if save > 0 {
if opt.Modified == nil {
opt.Modified = make(config.Config)
}
opt.Modified["pull"] = config.Struct2Config(pullConf)
if err = opt.Save(); err != nil {
opt.Error("save faild", zap.Error(err))
}
@@ -372,10 +297,7 @@ func (opt *Plugin) Push(streamPath string, url string, pusher IPusher, save bool
go pusher.startPush(pusher)
if save {
pushConfig.AddPush(url, streamPath)
if opt.Modified == nil {
opt.Modified = make(config.Config)
}
opt.Modified["push"] = config.Struct2Config(pushConfig)
opt.RawConfig.Get("push").Get("pushlist").Modify = pushConfig.PushList
if err = opt.Save(); err != nil {
opt.Error("save faild", zap.Error(err))
}