Documentation
¶
Overview ¶
Package httpx 提供管理 API 共用的 JSON 读写与错误响应。
Index ¶
- func ClientIP(r *http.Request) string
- func Error(w http.ResponseWriter, status int, format string, args ...any)
- func OK(w http.ResponseWriter, v any)
- func ParsePrefixes(list []string) ([]netip.Prefix, error)
- func PeerIP(r *http.Request) string
- func ReadJSON(r *http.Request, v any) error
- func SameOrigin(next http.Handler) http.Handler
- func SetProxyTrust(enable bool, extra []netip.Prefix)
- func ViaOf(r *http.Request) string
- func WithVia(r *http.Request, via string) *http.Request
- func WriteJSON(w http.ResponseWriter, status int, v any)
- type ErrorBody
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ClientIP ¶
ClientIP 返回请求的客户端地址。对端为可信代理时,依次从 X-Real-IP、X-Forwarded-For(自右向左跳过可信代理)中取得真实地址; 否则返回对端地址。
func Error ¶
func Error(w http.ResponseWriter, status int, format string, args ...any)
Error 输出错误 JSON。
func ParsePrefixes ¶ added in v0.5.0
ParsePrefixes 把 IP 或 CIDR 列表解析为地址段,单个 IP 视为 /32 或 /128。
func ReadJSON ¶
ReadJSON 解析请求体到 v,拒绝未知字段以尽早暴露前后端不一致。 要求 Content-Type 为 application/json:浏览器跨源发送该类型会触发预检,可阻止表单类 CSRF。
func SameOrigin ¶
SameOrigin 拒绝来自其他源的状态变更请求(同站不同端口、兄弟子域同样被拒绝)。 浏览器会为跨源请求带上 Origin 或 Sec-Fetch-Site;命令行工具通常两者都不带,予以放行。
func SetProxyTrust ¶ added in v0.5.0
SetProxyTrust 设置是否信任本机代理传来的客户端地址,extra 为额外信任的代理地址段。