From 5d00d1987b8db3672c93847180941c0442d93450 Mon Sep 17 00:00:00 2001 From: hupeh Date: Tue, 19 Sep 2023 23:58:46 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A8=A1=E5=9D=97=E5=8C=96=E4=B8=9A=E5=8A=A1?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkg/app/context.go | 55 ++++++++++++++++++++++++++++++++++++++++++++++ pkg/app/echo.go | 15 +++++++++++++ pkg/app/service.go | 16 ++++++++++++++ 3 files changed, 86 insertions(+) create mode 100644 pkg/app/context.go create mode 100644 pkg/app/echo.go create mode 100644 pkg/app/service.go diff --git a/pkg/app/context.go b/pkg/app/context.go new file mode 100644 index 0000000..5ebbbfe --- /dev/null +++ b/pkg/app/context.go @@ -0,0 +1,55 @@ +package app + +import ( + "context" + "github.com/labstack/echo/v4" + "sync" +) + +type Context struct { + context.Context + prefix string + store map[any]any + router *echo.Group + mu sync.RWMutex +} + +// Prefix 设置路由前缀 +func (c *Context) Prefix(prefix string) { + c.mu.Lock() + defer c.mu.Unlock() + if c.prefix != "" { + panic("already prefixed") + } + c.prefix = prefix +} + +// Routes 注册路由 +func (c *Context) Routes(routes Routable) { + c.mu.Lock() + defer c.mu.Unlock() + routes.InitRoutes(c.router) +} + +// Set 设置值 +func (c *Context) Set(key, val any) { + c.mu.Lock() + defer c.mu.Unlock() + c.store[key] = val +} + +// Get 获取值,只会获取通过 Set 方法设置的值 +func (c *Context) Get(key any) (any, bool) { + c.mu.RLock() + defer c.mu.RUnlock() + val, ok := c.store[key] + return val, ok +} + +// Value 获取值 +func (c *Context) Value(key any) any { + if val, ok := c.Get(key); ok { + return val + } + return c.Value(key) +} diff --git a/pkg/app/echo.go b/pkg/app/echo.go new file mode 100644 index 0000000..f8dcfd5 --- /dev/null +++ b/pkg/app/echo.go @@ -0,0 +1,15 @@ +package app + +import "github.com/labstack/echo/v4" + +type echoContext struct { + echo.Context + ctx *Context +} + +func (e *echoContext) Get(key string) any { + if val, ok := e.ctx.Get(key); ok && val != nil { + return val + } + return e.Context.Get(key) +} diff --git a/pkg/app/service.go b/pkg/app/service.go new file mode 100644 index 0000000..ce6690e --- /dev/null +++ b/pkg/app/service.go @@ -0,0 +1,16 @@ +package app + +import "github.com/labstack/echo/v4" + +type Service interface { + // Init 初始化服务 + Init(ctx *Context) error + // Start 启动服务 + Start() error + // Stop 停止服务 + Stop() error +} + +type Routable interface { + InitRoutes(r *echo.Group) +}