sin

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package sin 是一个纯标准库实现的 Go 迷你 Web 框架(无任何外部依赖),

一次请求的处理链路:

ServeHTTP(收集适用的组中间件)-> router.handle -> node.search(Trie 匹配)
-> 把业务 handler 追加到中间件链末尾 -> c.Next() 依次执行整条链

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewRouter

func NewRouter() *router

NewRouter 创建路由器并初始化两套数据结构与路由缓存(默认上限 defaultCacheLimit 条)。

func NewSin

func NewSin() *sin

NewSin 创建并返回一个框架引擎实例。 引擎内含一个 prefix 为空的根分组,根分组与其派生的子分组共用同一个 router, 因此引擎级与分组级注册共享同一套路由表。

Types

type Context

type Context struct {
	Writer     http.ResponseWriter // 原始响应写入器
	Request    *http.Request       // 原始请求
	Path       string              // 请求路径,如 /hello/sin
	Method     string              // 请求方法,标准大写形式(GET / POST ...)
	StatusCode int                 // 本次响应状态码,由 SetStatusCode 写入时记录
	ParamM     map[string]string   // 路由参数表,如 {"name": "sin"},由 router.handle 匹配后注入

	Keys map[string]any // 请求级键值表(懒初始化),供中间件与业务 handler 传值,见 Set/Get
	// contains filtered or unexported fields
}

Context 对 http.ResponseWriter 与 *http.Request 的薄封装,承载单次请求的上下文: 请求侧提供 Query / PostForm / Param 取参,响应侧提供 RetString / RetJson / RetHtml / RetData 输出; handlers + index 维护本次请求的处理链(组中间件在前、业务 handler 收尾),由 Next 驱动执行。

func NewContext

func NewContext(writer http.ResponseWriter, request *http.Request) *Context

NewContext 为一次请求构造 Context,从请求中提取 Path 与 Method。 index 初始化为 -1 是 Next 正确工作的前提(见 Next 注释)。

func (*Context) Abort

func (c *Context) Abort()

Abort 终止当前请求的后续处理链:常用于拦截型中间件(鉴权失败、CORS 预检应答等) 在写出响应后调用,阻止后续中间件与业务 handler 执行。 注意:Abort 前应先写出响应(如 401 / 204),否则整条链结束时仍是「无响应」状态, 会被 NotFound 兜底中间件按未处理写成 404。

func (*Context) BindJSON

func (c *Context) BindJSON(obj any) error

BindJSON 读取请求体并按 JSON 解析到 obj(obj 须为指针),自 sinWEB 移植。 请求体读取或 JSON 解析失败(含空 body)时返回 error,由调用方决定如何应答(如 400)。

func (*Context) Get

func (c *Context) Get(key string) (value any, ok bool)

Get 从请求级键值表读取一项;key 不存在(或从未 Set 过)时 ok 为 false,nil 表读取同样安全。

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted 报告当前请求的处理链是否已被 Abort 终止。

func (*Context) Next

func (c *Context) Next()

Next 执行处理链中剩余的 handler。实现为"先自增、再执行": 中间件内调用 c.Next() 会先执行完后续整条链,再回到自身继续(后置逻辑), 例如 Recovery 中间件正是靠这一语义用 defer 包裹后续链路。 若不先自增,嵌套调用会重复执行当前 handler,造成无限递归。

func (*Context) Param

func (c *Context) Param(key string) string

Param 读取路由参数,如模式 /hello/:name 匹配 /hello/sin 时 Param("name") == "sin"。 参数表由 router.handle 在 Trie 匹配成功后注入;未注入或 key 不存在时返回空字符串。

func (*Context) PostForm

func (c *Context) PostForm(key string) string

PostForm 读取表单参数(FormValue 会解析 body 中的表单,取不到时回退到 URL 查询参数)。

func (*Context) Query

func (c *Context) Query(key string) string

Query 读取 URL 查询参数,如 /hello?name=sin 中 Query("name") == "sin"。

func (*Context) RetData

func (c *Context) RetData(code int, data []byte)

RetData 原样写出字节数据,不设置 Content-Type,适合返回二进制内容。

func (*Context) RetHtml

func (c *Context) RetHtml(code int, name string, data any)

RetHtml 以 text/html 渲染并返回 HTML 模板。 name 为模板名(LoadHTMLGlob 加载的文件名,如 "index.html"),data 为模板数据。 模板尚未加载(或 Context 未关联引擎)时返回 500 而非 panic,并按约定记录 c.StatusCode,避免被 NotFound 兜底中间件误判为未响应而叠加 404; 渲染失败时响应已提交(可能是半截 HTML),仅记录服务端日志、不回传内部错误细节。

func (*Context) RetJson

func (c *Context) RetJson(code int, v any)

RetJson 将 v 序列化为 JSON 写出(Encoder 会自动追加换行符),Content-Type 为 application/json。 编码失败时状态码与响应头已提交、无法改写,仅记录服务端日志,不向客户端追加错误文本。

func (*Context) RetString

func (c *Context) RetString(code int, format string, a ...any)

RetString 以 text/plain 返回格式化文本,format 语法同 fmt.Sprintf。 注意顺序:响应头必须在 SetStatusCode(内部 WriteHeader)之前设置—— WriteHeader 会快照响应头,之后再改 header 在真实 net/http 服务器上不生效。

func (*Context) Set

func (c *Context) Set(key string, value any)

Set 向请求级键值表写入一项(懒初始化,避免为不使用的请求额外分配 map), 是中间件向业务 handler 传递数据的标准通道,如 RequestID、当前登录用户。

func (*Context) SetHeader

func (c *Context) SetHeader(key string, value string)

SetHeader 设置响应头,须在写出响应体之前调用。

func (*Context) SetStatusCode

func (c *Context) SetStatusCode(code int)

SetStatusCode 写出并记录响应状态码。

func (*Context) ShouldBind

func (c *Context) ShouldBind(obj any) bool

ShouldBind 是 BindJSON 的宽松版(自 sinWEB 移植):解析失败不返回错误、仅返回 false, 适合可选的请求体参数——如 GET 搜索接口带 JSON 过滤条件,没带或格式不对就用零值继续。

type H

type H map[string]any

H 是 map[string]any 的别名,用于以字面量形式快捷构造 JSON 数据。

type HandlerFunc

type HandlerFunc func(c *Context)

HandlerFunc 是框架统一的请求处理函数签名,所有业务 handler 都以该形式注册。

type ServerConfig

type ServerConfig struct {
	Addr            string        // 监听地址,如 ":9999"
	ReadTimeout     time.Duration // 读请求(含 body)超时,0 表示不限制
	WriteTimeout    time.Duration // 写响应超时,0 表示不限制
	ShutdownTimeout time.Duration // 优雅关闭时等待活跃请求处理完毕的上限
	MaxHeaderBytes  int           // 请求头字节上限,0 使用 http.Server 默认值
}

ServerConfig 是 RunWithConfig 的服务器配置(自 sinWEB 移植)。

func DefaultServerConfig

func DefaultServerConfig(addr string) ServerConfig

DefaultServerConfig 返回带默认值的服务器配置: 读写超时各 30s、优雅关闭等待 10s、请求头上限 1MB。

Directories

Path Synopsis
Package middleware 提供框架自带的通用中间件(日志、错误恢复等)。
Package middleware 提供框架自带的通用中间件(日志、错误恢复等)。

Jump to

Keyboard shortcuts

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