1 Star 0 Fork 0

csingo/cMiddleware

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Container.go 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
joe 提交于 2024-07-25 14:11 . update
package cMiddleware
import (
"net/http"
"reflect"
"sync"
"github.com/gin-gonic/gin"
)
type MiddlewareContainer struct {
lock sync.RWMutex
instances map[string]any
errorHandler func(ctx *gin.Context, err error)
}
func (i *MiddlewareContainer) Save(instance any) bool {
i.lock.Lock()
defer i.lock.Unlock()
app, name := instance.(MiddlewareInterface).MiddlewareName()
index := app + "." + name
i.instances[index] = instance
return true
}
func (i *MiddlewareContainer) Get(name string) any {
i.lock.RLock()
defer i.lock.RUnlock()
return i.instances[name]
}
func (i *MiddlewareContainer) Remove(name string) bool {
i.lock.Lock()
defer i.lock.Unlock()
delete(i.instances, name)
return true
}
func (i *MiddlewareContainer) Is(instance any) bool {
return reflect.TypeOf(instance).Implements(reflect.TypeOf((*MiddlewareInterface)(nil)).Elem())
}
func (i *MiddlewareContainer) Range(f func(instance any)) {
i.lock.RLock()
defer i.lock.RUnlock()
for _, item := range i.instances {
f(item)
}
}
func (i *MiddlewareContainer) SetErrorHandler(f func(ctx *gin.Context, err error)) {
i.errorHandler = f
}
var container = &MiddlewareContainer{
lock: sync.RWMutex{},
instances: make(map[string]any),
errorHandler: func(ctx *gin.Context, err error) {
ctx.String(http.StatusInternalServerError, "%s", err)
},
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/csingo/cMiddleware.git
git@gitee.com:csingo/cMiddleware.git
csingo
cMiddleware
cMiddleware
v0.4.4

搜索帮助