thttp

package
v0.0.0-...-8ccda10 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package thttp 的内置管理端点(Admin / pprof)。

Package thttp 提供 tingo 的 HTTP 服务层。

核心策略:所有多应用/多控制器的路由在注册期全部展开成 静态路由,运行时由 radix tree 直接命中, 不做任何字符串解析、反射查找或 map 查询,因此性能与原生等同。

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BindAndValid

func BindAndValid(c *core.Ctx, req any, scene ...string) bool

BindAndValid 将请求体/查询参数绑定到 req 指针,并用 tvalid 校验。 返回校验错误时,直接将 400 响应写入 c 并返回 true(调用方应中止)。

scene 为可选的场景名(验证场景):传入时按场景规则校验, 覆盖 req 上 tdb tag 的 scene 约束。空字符串表示不启用场景。

用法:

var req LoginReq
if thttp.BindAndValid(c, &req) {
    return
}
// 按场景校验:
if thttp.BindAndValid(c, &req, "create") {
    return
}

func ResolveAddr

func ResolveAddr(addr string) string

ResolveAddr 规整监听地址。允许直接写数字端口(如 "8081"), 自动补 ":" 前缀得到 ":8081";含 ":" 或为空则原样返回。

func WriteData

func WriteData(g *gin.Context, httpStatus, code int, message string, data any)

WriteData 写入标准 JSON 响应:{code, message, data}。

func WriteError

func WriteError(g *gin.Context, httpStatus, code int, err error)

WriteError 将错误标准化为 JSON 响应。 若 err 是 *tvalid.Errors(校验失败),返回 200 + 业务码 1 + 首条错误信息; 否则按传入 httpStatus 返回业务码(默认 1)。

func WriteOK

func WriteOK(g *gin.Context, data any)

WriteOK 写入成功响应(http 200,业务 code 0)。

func WritePage

func WritePage(g *gin.Context, list any, total int64, page, size int)

WritePage 写入分页列表响应。 list 为当页数据,total 为总记录数,page/size 为当前页码与每页大小。

Types

type AdminConfig

type AdminConfig struct {
	// EnablePprof 是否启用 pprof(默认 true)。
	EnablePprof bool
	// EnableStatus 是否启用状态页(默认 true)。
	EnableStatus bool
	// BasicAuth 可选的 HTTP Basic Auth 认证。空 map 表示不需要认证。
	BasicAuth map[string]string
	// PathPrefix 管理端点路径前缀(默认 "/__admin")。
	PathPrefix string
}

AdminConfig 管理端点配置。

func AdminConfigFromTree

func AdminConfigFromTree(tree tcfg.Reader) *AdminConfig

AdminConfigFromTree 从配置树读取管理端点配置。 约定路径:admin.enabled / admin.path_prefix / admin.enable_pprof / admin.enable_status / admin.basic_auth。

func DefaultAdminConfig

func DefaultAdminConfig() *AdminConfig

DefaultAdminConfig 返回默认管理端点配置。

type AdminOption

type AdminOption func(*AdminConfig)

AdminOption 是 AdminConfig 的建造选项。

func AdminBasicAuth

func AdminBasicAuth(users map[string]string) AdminOption

AdminBasicAuth 设置 BasicAuth 用户/密码。

func AdminEnablePprof

func AdminEnablePprof(enable bool) AdminOption

AdminEnablePprof 启用 pprof。

func AdminEnableStatus

func AdminEnableStatus(enable bool) AdminOption

AdminEnableStatus 启用状态页。

func AdminPathPrefix

func AdminPathPrefix(prefix string) AdminOption

AdminPathPrefix 设置路径前缀。

type Config

type Config struct {
	// Addr 是监听地址,如 :8080。
	Addr string

	// ReadTimeout 是读取整个请求的超时。
	ReadTimeout time.Duration
	// ReadHeaderTimeout 是读取请求头的超时。
	ReadHeaderTimeout time.Duration
	// WriteTimeout 是写响应的超时。
	WriteTimeout time.Duration
	// IdleTimeout 是 keep-alive 空闲超时。
	IdleTimeout time.Duration
	// ShutdownTimeout 是优雅关闭的最长等待时间。
	ShutdownTimeout time.Duration

	// MaxHeaderBytes 是请求头的最大字节数。
	MaxHeaderBytes int
	// MaxMultipartMemory 是 multipart 表单在内存中的最大字节数。
	MaxMultipartMemory int64
	// MaxBody 限制请求体大小(字节),0 表示不限制。
	// 防止恶意大 POST 打满连接/内存——超限时 c.Request.Body 读取返回
	// http.MaxBytesReader 对应的 ErrStatusRequestEntityTooLarge,由 Recover 中间件兜底。
	MaxBody int64
	// Version 是 API 版本前缀(如 "v1")。非空时所有路由自动挂载于 /{version} 下,
	// 例如 Version="v1" 时 /user/list 变为 /v1/user/list。便于无侵入地做 API 版本化。
	Version string

	// CertFile 与 KeyFile 非空时启用 HTTPS。
	CertFile string
	KeyFile  string

	// TrustedProxies 是可信代理列表,影响 ClientIP 的解析。
	TrustedProxies []string

	// RedirectTrailingSlash 允许自动补全/去除结尾斜杠后重定向。
	RedirectTrailingSlash bool
	// RedirectFixedPath 允许自动修正路径大小写后重定向。
	RedirectFixedPath bool
	// HandleMethodNotAllowed 开启后未匹配方法返回 405 而非 404。
	HandleMethodNotAllowed bool

	// BindRouteMeta 决定是否在上下文中绑定应用/控制器/方法名。
	// 关闭可减少一层闭包调用,用于极致性能场景。
	BindRouteMeta bool

	// PrintRoutes 启动时打印完整路由表。
	PrintRoutes bool
}

Config 是 HTTP 服务配置。

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine 是 tingo 的 HTTP 服务引擎,内嵌 gin.Engine。

func New

func New(opts ...Option) *Engine

New 创建绑定默认 App 的 Engine。

func NewWithApp

func NewWithApp(app *core.App, opts ...Option) *Engine

NewWithApp 创建绑定到指定框架 App 的 Engine。

func (*Engine) Boot

func (e *Engine) Boot() error

Boot 装配全部已注册的应用。幂等,重复调用无副作用。

装配顺序:

  1. 按 Priority 排序应用
  2. 逐个执行 Boot 钩子
  3. 建立应用路由组(域名绑定 / 前缀)
  4. 挂载应用级中间件
  5. 注册应用路由

全部工作在启动期完成,运行时不再有任何应用维度的解析。

func (*Engine) Config

func (e *Engine) Config() Config

Config 返回当前配置的副本。

func (*Engine) ConfigureAdminFromTree

func (e *Engine) ConfigureAdminFromTree(tree tcfg.Reader) error

ConfigureAdminFromTree 是框架内部的 ConfigureAtBoot 回调: 仅当配置文件中 admin.enabled = true 时才启用管理端点。

func (*Engine) ConfigureAtBoot

func (e *Engine) ConfigureAtBoot(configurators ...func(tcfg.Reader) error) *Engine

ConfigureAtBoot 注册配置消费者,在注册表加载后、业务路由装配前执行。

func (*Engine) EnableAdmin

func (e *Engine) EnableAdmin(opts ...AdminOption)

EnableAdmin 在 Engine 上启用管理端点。

用法:

engine.EnableAdmin(thttp.AdminPathPrefix("/__admin"), thttp.AdminEnablePprof(true))

func (*Engine) Gin

func (e *Engine) Gin() *gin.Engine

Gin 返回底层 *gin.Engine,用于使用 tingo 尚未封装的能力。

func (*Engine) HookAfterServe

func (e *Engine) HookAfterServe(hook Hook) *Engine

HookAfterServe 注册一个后置钩子(handler 返回后、响应写出前)。 典型场景:响应头追加、统一内容转换、缓存写入、性能监控。

func (*Engine) HookBeforeServe

func (e *Engine) HookBeforeServe(hook Hook) *Engine

HookBeforeServe 注册一个前置钩子(路由匹配后、handler 执行前)。 典型场景:统一鉴权、请求日志、RequestID 注入、跨域预检。

func (*Engine) PrintRouteTable

func (e *Engine) PrintRouteTable()

PrintRouteTable 以表格形式打印所有注册的路由。 支持 TINGO_LIST_ROUTES_METHOD 环境变量按方法筛选。

func (*Engine) Router

func (e *Engine) Router() core.Router

Router 返回根路由器,用于注册不属于任何应用的全局路由。

func (*Engine) Routes

func (e *Engine) Routes() []RouteInfo

Routes 返回已注册的全部路由,按路径排序。

func (*Engine) Run

func (e *Engine) Run() error

Run 启动服务并阻塞,收到 SIGINT/SIGTERM 时优雅关闭。

func (*Engine) RunContext

func (e *Engine) RunContext(ctx context.Context) error

RunContext 启动服务并阻塞,ctx 取消时优雅关闭。 调用方可以用它把 HTTP 服务纳入自己的进程生命周期。

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP 实现 http.Handler,便于测试与嵌入其他服务。 调用前会确保应用已装配。

func (*Engine) Shutdown

func (e *Engine) Shutdown() error

Shutdown 使用配置的超时时间优雅关闭服务。

func (*Engine) ShutdownContext

func (e *Engine) ShutdownContext(ctx context.Context) error

ShutdownContext 使用调用方提供的上下文关闭服务器和 App。

func (*Engine) Use

func (e *Engine) Use(mws ...core.Handler) *Engine

Use 注册全局中间件。必须在 Boot/Run 之前调用。

func (*Engine) UseGin

func (e *Engine) UseGin(mws ...gin.HandlerFunc) *Engine

UseGin 注册原生 gin 中间件,用于复用 gin 生态。

type Hook

type Hook func(ctx *core.Ctx) error

Hook 是生命周期钩子函数类型。

type HookType

type HookType int

HookType 定义钩子触发时机。

const (
	// HookBeforeServe 请求进入前执行(路由匹配后、handler 前)。
	HookBeforeServe HookType = iota + 1

	// HookAfterServe 请求处理完成后执行(handler 返回后、响应写出前)。
	HookAfterServe
)

type Option

type Option func(*Config)

Option 是配置修改函数。

func Addr

func Addr(addr string) Option

Addr 设置监听地址。

func DisableRouteMeta

func DisableRouteMeta() Option

DisableRouteMeta 关闭路由元信息绑定以换取极致性能。 关闭后 Ctx.App()/Controller()/Action() 将返回空串。

func IdleTimeout

func IdleTimeout(d time.Duration) Option

IdleTimeout 设置空闲超时。

func MaxMultipartMemory

func MaxMultipartMemory(n int64) Option

MaxMultipartMemory 设置 multipart 内存上限。

func PrintRoutes

func PrintRoutes() Option

PrintRoutes 启动时打印路由表。

func ReadTimeout

func ReadTimeout(d time.Duration) Option

ReadTimeout 设置读超时。

func ShutdownTimeout

func ShutdownTimeout(d time.Duration) Option

ShutdownTimeout 设置优雅关闭等待时间。

func TLS

func TLS(certFile, keyFile string) Option

TLS 启用 HTTPS。

func TrustedProxies

func TrustedProxies(proxies ...string) Option

TrustedProxies 设置可信代理。

func WithConfig

func WithConfig(cfg Config) Option

WithConfig 直接使用完整配置。

func WriteTimeout

func WriteTimeout(d time.Duration) Option

WriteTimeout 设置写超时。

type PrioritizedMiddleware

type PrioritizedMiddleware = core.WeightedMiddleware

PrioritizedMiddleware 是带优先级中间件(别名 core.WeightedMiddleware)。

数值越小越先执行(全局 -> 模块 -> 控制器 -> 动作 由小到大注册)。 同级按注册顺序。

type RouteInfo

type RouteInfo struct {
	// Method 是 HTTP 方法,ANY 表示全部方法。
	Method string
	// Path 是完整路径。
	Path string
	// App 是所属应用名。
	App string
	// Handler 是处理器的可读名称。
	Handler string
}

RouteInfo 是一条已注册路由的信息。

Directories

Path Synopsis
Package middleware 提供 tingo 内置中间件。
Package middleware 提供 tingo 内置中间件。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL