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

70 lines
1.7 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"
"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 {
f := filepath.Join(dirPath, entry)
p, err := plugin.Open(f)
if err != nil {
logs.Error(err, "读取插件错误", f)
continue
}
name := filepath.Ext(entry)
name = str.FirstUpper(entry[0 : len(entry)-len(name)])
pl, err := p.Lookup(name)
if err != nil {
logs.Error(err, "插件lookup错误", f)
continue
}
plu, ok := pl.(func(*wp.Handle))
if !ok {
logs.Error(errors.New("switch func(*wp.Handle) fail"), "插件转换错误", f)
continue
}
RegisterPlugin(name, plu)
}
}