contracts/http.go

118 lines
2.4 KiB
Go

package contracts
import (
"net/http"
"github.com/samber/do"
)
var defaultWsClientGroup WsClientGroup = "__DEFAULT__"
var wsClientID WsClientID = 0
type Http interface {
Start() error
Stop() error
Restart() 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()
// 数据库权限
AuthDB() ResAuthDB
}
type WsController interface {
HttpController
// 请求处理
ExecuteWS(GlobalParams) error
// 获取 Ws 客户端
WsClient() WsClient
// 获取 Ws 标识
WsClientId(GlobalParams) WsClientID
// 获取 Ws 分组
WsClientGroup(GlobalParams) WsClientGroup
}
type HttpHandleController struct {
Controller
request *http.Request
}
type WsHandleController struct {
HttpController
ws WsClient
}
func (this HttpHandleController) Request() *http.Request {
return this.request
}
func (this HttpHandleController) Route() Route {
return this.Request().Context().Value(RouteCtx{Name: "Route"}).(Route)
}
func (this HttpHandleController) User() User {
return this.Request().Context().Value(RouteCtx{Name: "User"}).(User)
}
func (this HttpHandleController) Call(code string, params map[string]any, category ...RouteCategory) (HttpResponse, error) {
return do.MustInvoke[Router](this.Container()).Call(this.Request(), code, params, category...)
}
func (HttpHandleController) Execute(params GlobalParams) any {
return nil
}
func (HttpHandleController) AuthDB() ResAuthDB {
return ResAuthOn
}
func (WsHandleController) ExecuteWS(params GlobalParams) error {
return nil
}
func (this WsHandleController) WsClient() WsClient {
return this.ws
}
func (WsHandleController) WsClientId(GlobalParams) WsClientID {
wsClientID++
return wsClientID
}
func (WsHandleController) WsClientGroup(GlobalParams) WsClientGroup {
return defaultWsClientGroup
}
func NewHttpController(container *do.Injector, request *http.Request) HttpController {
return &HttpHandleController{
Controller: &BaseController{container},
request: request,
}
}
func NewWsController(ws WsClient, ctr HttpController) WsController {
return &WsHandleController{
HttpController: ctr,
ws: ws,
}
}