go项目脚手架
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.3 KiB

package runtime
import (
"context"
"errors"
"github.com/labstack/echo/v4"
"slices"
)
// 注册的网络服务组件
var servlets []Servlet
// Servlet 网络服务组件接口
type Servlet interface {
// Name 服务名称
Name() string
// Priority 优先级,用于启动和销毁的执行顺序
Priority() int
// Init 初始化服务
Init(ctx context.Context) error
// Routes 注册路由
Routes() []Routable
// Start 非阻塞方式启动服务
Start() error
// Stop 停止服务
Stop() error
}
func Reset() error {
if len(servlets) == 0 {
return nil
}
if ctx == nil {
return errors.New("servlets is running")
}
servlets = nil
return nil
}
// Use 注册服务
func Use(servlets ...Servlet) error {
if len(servlets) == 0 {
return nil
}
for i := 0; i < len(servlets); i++ {
if !use(servlets[i]) {
return errors.New("service already registered")
}
}
slices.SortFunc(servlets, func(a, b Servlet) int {
return b.Priority() - a.Priority() // 按优先级排序
})
return nil
}
func use(servlet Servlet) bool {
exists := slices.ContainsFunc(servlets, func(s Servlet) bool {
return s.Name() == servlet.Name()
})
if !exists {
servlets = append(servlets, servlet)
return true
}
return false
}
type Routable interface {
InitRoutes(*echo.Group)
}