104 lines
2.9 KiB
Go
104 lines
2.9 KiB
Go
package contracts
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
|
|
"git.fsdpf.net/go/req"
|
|
"github.com/samber/do/v2"
|
|
)
|
|
|
|
var defaultWsClientGroup WsClientGroup = "__DEFAULT__"
|
|
var wsClientID WsClientID = 0
|
|
|
|
type Http interface {
|
|
// Start 启动 HTTP 服务。
|
|
Start() error
|
|
|
|
// Shutdown 停止 HTTP 服务,等待当前请求处理完成后退出。
|
|
Shutdown() error
|
|
|
|
// Restart 重启 HTTP 服务,先停止再重新加载路由并启动。
|
|
Restart() error
|
|
|
|
// Invoke 在进程内直接调用 HTTP 路由处理器,不通过网络。
|
|
//
|
|
// 参数:
|
|
// - method: HTTP 方法,如 "GET"、"POST" 等。
|
|
// - path: 请求路径,如 "/api/user/list"。
|
|
// - body: 请求体,无请求体时传 nil。
|
|
// - headers: 附加请求头键值对,无需额外请求头时传 nil。
|
|
//
|
|
// 返回:
|
|
// - *http.Response: 包含状态码、响应头及响应体的结果。
|
|
// - error: 构造请求失败时返回错误。
|
|
Invoke(method, path string, body io.Reader, header http.Header) (*http.Response, error)
|
|
}
|
|
|
|
type HttpController interface {
|
|
Controller
|
|
|
|
// User 返回当前请求的认证用户信息。
|
|
User() req.User
|
|
|
|
// Request 返回当前 HTTP 请求对象。
|
|
Request() *http.Request
|
|
|
|
// Execute 处理请求并返回响应数据。
|
|
Execute(req.GlobalParams) any
|
|
|
|
// Route 返回当前请求匹配到的路由信息。
|
|
Route() req.Route
|
|
|
|
// Call 在进程内以路由 code 发起内部调用,等同于向自身发送 HTTP 请求。
|
|
//
|
|
// 参数:
|
|
// - code: 路由标识码。
|
|
// - params: 附加请求参数。
|
|
// - category: 可选的路由匹配选项。
|
|
//
|
|
// 返回:
|
|
// - req.HttpResponse: 内部调用的响应结果。
|
|
// - error: 调用失败时返回错误。
|
|
Call(code string, params map[string]any, category ...req.RouteMatchOption) (req.HttpResponse, error)
|
|
|
|
// AuthDB 返回当前控制器的数据库权限模式。
|
|
AuthDB() req.ResAuthDB
|
|
}
|
|
|
|
type HttpHandleController struct {
|
|
Controller
|
|
request *http.Request
|
|
}
|
|
|
|
func (this HttpHandleController) Request() *http.Request {
|
|
return this.request
|
|
}
|
|
|
|
func (this HttpHandleController) Route() req.Route {
|
|
return this.Request().Context().Value(req.RouteCtx{Name: "Route"}).(req.Route)
|
|
}
|
|
|
|
func (this HttpHandleController) User() req.User {
|
|
return this.Request().Context().Value(req.RouteCtx{Name: "User"}).(req.User)
|
|
}
|
|
|
|
func (this HttpHandleController) Call(code string, params map[string]any, opts ...req.RouteMatchOption) (req.HttpResponse, error) {
|
|
return do.MustInvoke[req.Router](this.Container()).Call(this.Request(), code, params, opts...)
|
|
}
|
|
|
|
func (HttpHandleController) Execute(params req.GlobalParams) any {
|
|
return nil
|
|
}
|
|
|
|
func (HttpHandleController) AuthDB() req.ResAuthDB {
|
|
return req.ResAuthOn
|
|
}
|
|
|
|
func NewHttpController(container do.Injector, request *http.Request) HttpController {
|
|
return &HttpHandleController{
|
|
Controller: &BaseController{container},
|
|
request: request,
|
|
}
|
|
}
|