This commit is contained in:
Star 2024-01-25 16:00:54 +08:00
parent c9ba31e140
commit b70fd3a230
3 changed files with 92 additions and 23 deletions

25
.gitignore vendored
View File

@ -1,23 +1,2 @@
# ---> Go
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
.*
/go.sum

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module github.com/api-go/plugin
go 1.17

87
plugin.go Normal file
View File

@ -0,0 +1,87 @@
package plugin
import (
"reflect"
"sync"
)
type Config map[string]interface{}
type Plugin struct {
Id string
Name string
Objects map[string]interface{}
ConfigSample string
JsCode string
Init func(map[string]interface{})
}
type Context struct {
injects map[string]interface{}
data map[string]interface{}
}
func NewContext(injects map[string]interface{}) *Context {
return &Context{
injects: injects,
data: map[string]interface{}{},
}
}
func (ctx *Context) SetInject(obj interface{}) {
ctx.injects[reflect.ValueOf(obj).Type().String()] = obj
}
func (ctx *Context) GetInject(typ string) interface{} {
return ctx.injects[typ]
}
func (ctx *Context) GetData(k string) interface{} {
return ctx.data[k]
}
func (ctx *Context) SetData(k string, v interface{}) {
ctx.data[k] = v
}
var pluginById = map[string]*Plugin{}
var pluginsLock = sync.RWMutex{}
func Register(p Plugin) {
pluginsLock.Lock()
defer pluginsLock.Unlock()
pluginById[p.Id] = &p
}
func Update(plugName, objectName string, value interface{}) {
pluginsLock.RLock()
p := pluginById[plugName]
pluginsLock.RUnlock()
if p != nil {
pluginsLock.Lock()
if p.Objects == nil {
p.Objects = map[string]interface{}{}
}
p.Objects[objectName] = value
pluginsLock.Unlock()
}
}
func List() []Plugin {
pluginsLock.RLock()
defer pluginsLock.RUnlock()
out := make([]Plugin, len(pluginById))
i := 0
for _, p := range pluginById {
out[i] = *p
i++
}
return out
}
func Get(id string) *Plugin {
pluginsLock.RLock()
defer pluginsLock.RUnlock()
return pluginById[id]
}