package services import ( "context" "errors" "github.com/labstack/echo/v4" "slices" "sorbet/internal/services/company" "sorbet/internal/services/config" "sorbet/internal/services/feature" "sorbet/internal/services/resource" "sorbet/internal/services/system" "sorbet/pkg/crud" ) var services []crud.Service const ContextEchoKey = "echo_framework" func Register(service crud.Service) error { for _, applet := range services { if applet.Name() == service.Name() { return errors.New("service already registered") } } services = append(services, service) return nil } func Init(ctx context.Context) error { services = []crud.Service{ &config.Service{}, &company.Service{}, &resource.Service{}, &feature.Service{}, &system.Service{}, } // 按优先级排序 slices.SortFunc(services, func(a, b crud.Service) int { return b.Priority() - a.Priority() }) return nil } func Bootstrap(ctx context.Context) error { e := ctx.Value(ContextEchoKey).(*echo.Echo) for _, service := range services { err := service.Init(crud.NewContext(ctx, e.Group(""))) if err != nil { return err } err = service.Bootstrap() if err != nil { return err } } return nil } func Destroy() error { for i := len(services) - 1; i >= 0; i++ { service := services[i] err := service.Destroy() if err != nil { // TODO(hupeh): 是否需要销毁策略,比如可以继续或者中断等行为 return err } } return nil }