1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
plugins.go 1.52 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2023-12-12 14:24 . plugin
package plugins
import (
"context"
"sync"
)
const (
KAlarm = "alarm"
)
type Command struct {
Cmd string
Data interface{}
}
type Data struct {
Error error
Data interface{}
}
type Chan chan Data
type Plugin interface {
// Do
// name is plugin's name
// key parameter is custom defined
// d parameter is can use Command or custom
// return is custom
Do(ctx context.Context, key string, d interface{}) (interface{}, error)
DoChan(ctx context.Context, key string, d interface{}) (Chan, error)
}
type Plugins struct {
locker sync.RWMutex
plus map[string]Plugin
}
var plugins *Plugins
var def *defaultPlugin
func init() {
def = &defaultPlugin{}
plugins = &Plugins{
plus: make(map[string]Plugin),
}
}
func Get(name string) Plugin {
plugins.locker.RLock()
defer plugins.locker.RUnlock()
if p, exist := plugins.plus[name]; exist {
return p
}
return def
}
func Add(name string, p Plugin) {
plugins.locker.Lock()
defer plugins.locker.Unlock()
plugins.plus[name] = p
}
func Remove(name string) {
plugins.locker.Lock()
defer plugins.locker.Unlock()
delete(plugins.plus, name)
}
func Do(name string, ctx context.Context, key string, d interface{}) (interface{}, error) {
p := Get(name)
return p.Do(ctx, key, d)
}
func DoChan(name string, ctx context.Context, key string, d interface{}) (Chan, error) {
p := Get(name)
return p.DoChan(ctx, key, d)
}
// DoWithError 只关心error
func DoWithError(name string, ctx context.Context, key string, d interface{}) error {
_, err := Do(name, ctx, key, d)
return err
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.88

搜索帮助