package contracts import ( "net/http" "github.com/samber/do" ) type Controller interface { // 初始化 Init() error // 获取 Container Container() *do.Injector // 派遣一个任务 Dispatch(job string, payload any, u User) error } type HttpController interface { Controller // 获取用户信息 User() User // 获取请求信息 Request() *http.Request // 请求处理 Execute(GlobalParams) any // 路由信息 Route() Route // 内部调用 Call(code string, params map[string]any, category ...RouteCategory) (HttpResponse, error) // 内部调用 // Invoke() } type WsController interface { HttpController // 请求处理 ExecuteWS(GlobalParams) error // 获取 Ws 客户端 WsClient() WsClient // 获取 Ws 标识 WsClientId(GlobalParams) WsClientID // 获取 Ws 分组 WsClientGroup(GlobalParams) WsClientGroup } type BaseController struct { container *do.Injector } type HttpBaseController struct { Controller request *http.Request } type WsBaseController struct { HttpController ws WsClient } var defaultWsClientGroup WsClientGroup = "__DEFAULT__" var wsClientID WsClientID = 0 func (this BaseController) Container() *do.Injector { return this.container } func (BaseController) Init() error { return nil } func (this BaseController) Dispatch(job string, payload any, u User) error { return do.MustInvoke[JobService](this.Container()).Dispatch(job, payload, u) } func (this HttpBaseController) Request() *http.Request { return this.request } func (this HttpBaseController) Route() Route { return this.Request().Context().Value(RouteCtx{Name: "Route"}).(Route) } func (this HttpBaseController) User() User { return this.Request().Context().Value(RouteCtx{Name: "User"}).(User) } func (this HttpBaseController) Call(code string, params map[string]any, category ...RouteCategory) (HttpResponse, error) { return do.MustInvoke[Router](this.Container()).Call(this.Request(), code, params, category...) } func (HttpBaseController) Execute(params GlobalParams) any { return nil } func (WsBaseController) ExecuteWS(params GlobalParams) error { return nil } func (this WsBaseController) WsClient() WsClient { return this.ws } func (WsBaseController) WsClientId(GlobalParams) WsClientID { wsClientID++ return wsClientID } func (WsBaseController) WsClientGroup(GlobalParams) WsClientGroup { return defaultWsClientGroup } func NewBaseController(container *do.Injector) Controller { return &BaseController{container} } func NewHttpBaseController(container *do.Injector, request *http.Request) HttpController { return &HttpBaseController{ Controller: &BaseController{container}, request: request, } } func NewWsBaseController(ws WsClient, ctr HttpController) WsController { return &WsBaseController{ HttpController: ctr, ws: ws, } }