BREAKING CHANGES: - Guard interface: Guard(ctx Ctx) error; returning error short-circuits (subsequent guards and the method no longer execute) - Wired[T]() (*T, error); New() may return error; failed wiring is sticky - BindService/BindGuard/BindRoute return error; routes accept guards (guards receive merged query/form params as Ctx.State) - registration panics after Start; Ctx.Ip honors X-Forwarded-For/X-Real-IP - internal errors sanitized to fixed client messages FIXES: - int64 precision loss: /cell data decoded from raw JSON bytes and responses serialized with json.Number (no float64 round-trip) - enum values range-checked before uint8 conversion (256 no longer truncates to 0 and slips through) - logger: files failing name parsing are no longer deleted; log channel never blocks request goroutines; ConfigLogger is race-free; logWriterWorker unlock bug fixed - stream writer panics recovered (process no longer crashes); streamDone closed exactly once - generated Go client emits definitions for pointer-to-enum/struct fields - anonymous structs rejected at registration; isPrivate safe on empty names - removed dead Result.Id and RequestInfo.Type ADDITIONS: - graceful shutdown (Shutdown), StartOn, server timeouts by default (Read 60s/Idle 120s/Write off), SetTimeouts/SetMaxConcurrency - big-int-safe JSON in the generated TS client (>2^53 as BigInt) - example/ demo services and cmd/genexample artifact generator
52 lines
1.5 KiB
Go
52 lines
1.5 KiB
Go
package fun
|
|
|
|
import (
|
|
"net"
|
|
"strings"
|
|
|
|
"github.com/valyala/fasthttp"
|
|
)
|
|
|
|
// clientIP 解析客户端真实 IP。
|
|
// 优先级:X-Forwarded-For > X-Real-IP > RemoteAddr。
|
|
// 部署在反向代理(nginx 等)后时由代理写入这两个头;
|
|
// 直连无代理头时回退到连接对端地址
|
|
func clientIP(ctx *fasthttp.RequestCtx) string {
|
|
// 1. X-Forwarded-For 取最后一个非空段:
|
|
// 该段由离服务最近的一层代理追加,是代理链中最可信的一段
|
|
if ip := lastNonEmpty(string(ctx.Request.Header.Peek("X-Forwarded-For"))); ip != "" {
|
|
return toLoopback(ip)
|
|
}
|
|
|
|
// 2. X-Real-IP(通常由 nginx 设置)
|
|
if ip := strings.TrimSpace(string(ctx.Request.Header.Peek("X-Real-IP"))); ip != "" {
|
|
return toLoopback(ip)
|
|
}
|
|
|
|
// 3. 回退到连接对端地址;无对端或未指定地址(0.0.0.0,测试/直驱场景)按本机处理
|
|
if remote := ctx.RemoteIP(); remote != nil && !remote.IsUnspecified() {
|
|
return toLoopback(remote.String())
|
|
}
|
|
return "127.0.0.1"
|
|
}
|
|
|
|
// lastNonEmpty 取 X-Forwarded-For 中最后一个非空段
|
|
// X-Forwarded-For: client, proxy1, proxy2
|
|
func lastNonEmpty(xff string) string {
|
|
parts := strings.Split(xff, ",")
|
|
for i := len(parts) - 1; i >= 0; i-- {
|
|
if ip := strings.TrimSpace(parts[i]); ip != "" {
|
|
return ip
|
|
}
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// toLoopback 回环地址统一返回 127.0.0.1,其余原样返回
|
|
func toLoopback(ip string) string {
|
|
if parsed := net.ParseIP(ip); parsed != nil && parsed.IsLoopback() {
|
|
return "127.0.0.1"
|
|
}
|
|
return ip
|
|
}
|