wp-go/app/plugins/wphandle/handle.go

73 lines
1.8 KiB
Go
Raw Normal View History

2023-03-02 15:49:28 +00:00
package wphandle
import (
2023-05-04 11:46:06 +00:00
"errors"
2023-05-04 12:37:06 +00:00
"github.com/fthvgb1/wp-go/app/pkg/config"
"github.com/fthvgb1/wp-go/app/pkg/logs"
2023-05-08 13:43:20 +00:00
"github.com/fthvgb1/wp-go/app/plugins/wphandle/apply"
2023-05-04 12:37:06 +00:00
"github.com/fthvgb1/wp-go/app/plugins/wphandle/enlightjs"
"github.com/fthvgb1/wp-go/app/plugins/wphandle/hiddenlogin"
"github.com/fthvgb1/wp-go/app/theme/wp"
2023-05-04 11:46:06 +00:00
str "github.com/fthvgb1/wp-go/helper/strings"
"github.com/fthvgb1/wp-go/safety"
"path/filepath"
"plugin"
2023-03-02 15:49:28 +00:00
)
2023-05-04 11:46:06 +00:00
var plugins = func() *safety.Map[string, func(*wp.Handle)] {
m := safety.NewMap[string, func(*wp.Handle)]()
2023-05-04 12:37:06 +00:00
m.Store("Enlightjs", enlightjs.EnlighterJS)
m.Store("HiddenLogin", hiddenlogin.HiddenLogin)
2023-05-04 11:46:06 +00:00
return m
}()
2023-03-02 15:49:28 +00:00
2023-05-04 11:46:06 +00:00
func RegisterPlugin(name string, fn func(*wp.Handle)) {
plugins.Store(name, fn)
2023-03-02 15:49:28 +00:00
}
2023-04-25 12:58:22 +00:00
func UsePlugins(h *wp.Handle, calls ...string) {
calls = append(calls, config.GetConfig().Plugins...)
2023-03-02 15:49:28 +00:00
for _, call := range calls {
2023-05-04 12:37:06 +00:00
call = str.FirstUpper(call)
2023-05-04 11:46:06 +00:00
if fn, ok := plugins.Load(call); ok {
2023-03-02 15:49:28 +00:00
fn(h)
}
}
}
2023-05-04 11:46:06 +00:00
func LoadPlugins() {
dirPath := config.GetConfig().PluginPath
if dirPath == "" {
return
}
glob, err := filepath.Glob(filepath.Join(dirPath, "*.so"))
if err != nil {
logs.Error(err, "读取插件目录错误", dirPath)
return
}
for _, entry := range glob {
2023-05-04 13:06:27 +00:00
p, err := plugin.Open(entry)
2023-05-04 11:46:06 +00:00
if err != nil {
2023-05-04 13:06:27 +00:00
logs.Error(err, "读取插件错误", entry)
2023-05-04 11:46:06 +00:00
continue
}
name := filepath.Ext(entry)
2023-05-04 13:06:27 +00:00
name = filepath.Base(entry[0 : len(entry)-len(name)])
name = str.FirstUpper(name)
2023-05-04 11:46:06 +00:00
pl, err := p.Lookup(name)
if err != nil {
2023-05-04 13:06:27 +00:00
logs.Error(err, "插件lookup错误", entry)
2023-05-04 11:46:06 +00:00
continue
}
plu, ok := pl.(func(*wp.Handle))
if !ok {
2023-05-04 13:06:27 +00:00
logs.Error(errors.New("switch func(*wp.Handle) fail"), "插件转换错误", entry)
2023-05-04 11:46:06 +00:00
continue
}
RegisterPlugin(name, plu)
}
2023-05-08 13:43:20 +00:00
apply.SetFn(func(h *wp.Handle) {
UsePlugins(h)
})
2023-05-04 11:46:06 +00:00
}