119 Commits

Author SHA1 Message Date
xfy
8ae4add922 fix: address code review feedback
- proxyDebugLog: move Enabled() guard to call sites to avoid allocations
- proxyDebugLog: add default case for unsupported types
- static routes: remove unintended regex support to match original behavior
2026-06-03 14:29:30 +08:00
xfy
4678cb5483 refactor: use testutil helpers in server tests 2026-06-03 14:19:22 +08:00
xfy
684122dbf7 refactor: extract registerRoute helper to reduce repetition 2026-06-03 13:55:18 +08:00
xfy
728a9f454b fix(server,app,config): address code review findings
- Fix FD leak in DupListener: close *os.File after net.FileListener
- Add cleanup of partially-duped listeners on DupListener failure
- Make reload timeout configurable via shutdown.reload_timeout
- Handle filepath.Abs errors in processIncludes instead of ignoring
- Use net.ParseIP in isAnyAddr for robust IPv6 support
2026-06-03 13:16:05 +08:00
xfy
556d40ceb0 fix(matcher,server): use ConflictError in AddNamed and add tests
Make AddNamed return *ConflictError for consistency with other Add*
methods so handleRegistrationError treats named location conflicts as
warnings instead of fatal errors. Add tests for handleRegistrationError
covering both conflict and fatal error paths.
2026-06-03 11:47:06 +08:00
xfy
f58f194752 fix(server): serialize listener creation in multi-server mode
Remove VHost fallback during graceful upgrade. Serialize listener
creation before parallel router/middleware setup to prevent concurrent
inherited listener consumption. Fix tcpAddrMatch to match when either
side is any-addr (0.0.0.0/::).
2026-06-03 11:44:14 +08:00
xfy
f3f78b24a8 feat(server,app): implement proper config hot reload via SIGHUP
createListener now checks pre-set s.listeners (Path 2) for hot reload,
not just upgradeManager.IsChild() (Path 1). Add DupListener to dup FDs
so old/new servers own independent listeners. Reload rebuilds HTTP/2
and HTTP/3. Add matchInheritedListener with TCP any-addr matching.
Add requiresFullRestart with VHost server count detection.
2026-06-03 11:42:45 +08:00
xfy
38bb743781 fix(server): handle LocationEngine registration errors properly
Add typed ConflictError for path conflicts, change register functions
to return errors, handle conflicts as warnings and fatal errors as
startup failures. Remove all 20 instances of ignored Add* return values.
2026-06-03 10:12:09 +08:00
xfy
ac66ea5534 fix(server): use atomic.Bool for Server.running to eliminate data race
Server.running was a plain bool accessed from multiple goroutines
(start/stop/signal handlers). Convert to atomic.Bool with
Store/Load to make all accesses safe for concurrent use.

Updates all test files to use the new atomic API.
2026-06-03 01:19:23 +08:00
xfy
b6018ff9c9 test: add t.Parallel() to enable parallel test execution
Add t.Parallel() to 110 test functions across 3 test files:
- internal/loadbalance/balancer_test.go (42 tests)
- internal/config/validate_test.go (21 tests)
- internal/server/status_test.go (47 tests)

This reduces total test time from ~3 minutes to ~34 seconds (5.4x faster).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:57:23 +08:00
xfy
8643a0aff9 refactor: improve error handling and fix linter warnings
- Add nolint comments for type assertion errcheck in gjson/encode.go
  (switch case guarantees type safety)
- Handle fasthttp.Serve errors in benchmark mock backends
- Rename error variables to avoid shadowing in server.go
- Use underscore for unused loop variables

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:32:06 +08:00
xfy
c157be1ce5 refactor(cache): remove unused disk/tiered cache and add helper functions
Remove unused disk cache, tiered cache, purge, and config loader code.
Add HashPathWithMethod and MatchPattern helpers for future cache purge API.
Update test to use new mock backend API with ResponseBody field.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 17:26:19 +08:00
xfy
25d93c25fa refactor: remove unused code and fix formatting
- Remove unused benchmark/tools package
- Make ValidAlgorithms private (validAlgorithms) in loadbalance
- Remove dead code (_ = result) in lua/api_socket_tcp.go
- Fix code formatting with goimports

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 16:58:45 +08:00
xfy
986ebdf207 fix(lua): enable file watch by default for hot reload
EnableFileWatch was false by default (Go bool zero value) when
global_settings was not configured. Now defaults to true to enable
Lua script hot reload without server restart.

Also fix indentation in init.go default value settings.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 13:45:55 +08:00
xfy
8f3c304837 fix(lua): register Lua routes in multi-server mode
Add registerLuaRoutes method for router-based route registration
and call it in startMultiServerMode to fix Lua routes not working
when multiple servers are configured.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 13:41:26 +08:00
xfy
a5b5a085cc feat(lua): add Lua route registration in server startup
Add call to registerLuaRoutesWithLocationEngine between proxy and static
route registration, ensuring correct routing order: proxy -> lua -> static.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 11:44:39 +08:00
xfy
669f9c975b feat(lua): add registerLuaRoutesWithLocationEngine for Lua route handling
Add two new functions to router.go:
- registerLuaRoutesWithLocationEngine: registers Lua scripts with Route
  config to LocationEngine with support for exact/prefix/regex matching
- wrapRoutedHandler: wraps route handlers with basic middleware chain
  (accesslog + errorintercept)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 11:42:06 +08:00
xfy
dff88449d5 feat(lua): skip routed scripts in middleware builder
Scripts with Route config are handled by LocationEngine, so skip them
in buildLuaMiddlewares to avoid duplicate processing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 11:38:40 +08:00
xfy
f3f92c7922 feat(lua): add LState pool configuration and fix coroutine error handling
- Add LStatePoolInitialSize and LStatePoolMaxSize config fields
- Set pool defaults to 100 initial / 1000 max (matching MaxConcurrentCoroutines)
- Fix middleware to return 500 on coroutine init failure instead of continuing
- Pass pool config from server init to Lua engine with zero-value fallbacks

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 11:13:23 +08:00
xfy
5d9ef8e611 refactor(server): extract static handler configuration
Extract duplicate static handler configuration logic from
registerStaticHandlersWithLocationEngine and registerStaticHandlers
into a new configureStaticHandler method.

- Create configureStaticHandler() to handle alias, cache, gzip,
  symlink, internal, expires, and autoIndex configuration
- Both registration functions now call the shared configuration method
- Registration logic remains separate (LocationEngine vs Router)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:10:52 +08:00
xfy
8c96c4384f fix(status): use version package instead of hardcoded version
Replace hardcoded "1.0.0" with version.Version to show the actual
build version injected via -ldflags.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 17:46:32 +08:00
xfy
9c46c8bab8 fix(server): register status and pprof handlers in multi-server mode
In startMultiServerMode, status and pprof handlers were not registered,
causing /_status and /debug/pprof endpoints to return 404. Now these
handlers are registered on the server with default: true, consistent
with startVHostMode behavior. Also fixed cache API registration to
use default server instead of first server.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 17:44:57 +08:00
xfy
03c27c8d95 fix(static): add missing AutoIndex and Internal settings in registerStaticHandlers
The registerStaticHandlers function (used in multi-server mode) was missing
AutoIndex and Internal configuration that registerStaticHandlersWithLocationEngine
already had. This caused auto_index to not work in multi-server mode.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-07 16:32:41 +08:00
xfy
b62a3f12da feat(handler): add autoindex module for directory listing
Add nginx-like autoindex functionality with three output formats:
- HTML: styled directory listing with sortable columns
- JSON: structured API-friendly output
- XML: machine-readable format

Configuration options:
- auto_index: enable/disable directory listing
- auto_index_format: output format (html/json/xml)
- auto_index_localtime: use local time instead of GMT
- auto_index_exact_size: show exact bytes vs human-readable

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 15:11:34 +08:00
xfy
d269940d8b style: fix formatting issues
- Add missing newlines at end of files
- Fix indentation in ssl.go
- Remove extra blank lines

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 13:42:53 +08:00
xfy
f145a8770e refactor: modernize code with Go 1.22+ features
Apply modern Go patterns across the codebase:
- Replace `interface{}` with `any` (Go 1.18+)
- Use `for range n` instead of `for i := 0; i < n; i++` (Go 1.22+)
- Replace `sort.Slice` with `slices.Sort` from slices package
- Simplify sync.WaitGroup patterns with errgroup where appropriate
- Add Makefile targets for modernize analyzer

Total: 84 files updated, net reduction of 79 lines

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-30 10:37:45 +08:00
xfy
d25c7b21a6 refactor(server): extract createProxyForConfig helper
- 新增 createProxyForConfig 统一代理创建逻辑
- 重构 registerProxyRoutesWithLocationEngine 和 registerProxyRoutes
- 消除约 40 行重复代码

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 17:52:40 +08:00
xfy
7eaea845e7 refactor(server): extract createFastServer helper
- 新增 createFastServer 统一 fasthttp.Server 创建
- 消除 startSingleMode/startVHostMode/startMultiServerMode 中的重复代码
- multi_server 模式现在也支持高并发优化配置

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 17:48:40 +08:00
xfy
91e04222b3 refactor: 统一 IP 白名单解析和 excludeSet 构建
Batch 1 重构:
- 新增 utils.ParseIPAllowList 统一 IP/CIDR 解析(含 localhost 特殊处理)
- pprof.go/status.go/purge.go 改用统一函数,减少 ~66 行重复代码
- 新增 loadbalance.buildExcludeSet 统一排除集合构建
- 更新 pprof_test.go 适配统一字段 allowed []net.IPNet

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-29 16:18:52 +08:00
xfy
cf2fcca7e8 refactor: 提取公共逻辑、消除重复代码、加强错误处理
- 提取 App 公共逻辑到 app_common.go,消除 app.go/app_windows.go 重复定义
- 提取 Server 生命周期/中间件/路由逻辑到独立文件(lifecycle.go/middleware_builder.go/router.go)
- 提取 Proxy 缓存处理/头部修改/目标选择到独立模块
- 提取 CheckIPAccess/CheckTokenAuth 到 utils/httperror.go,消除 status/purge 重复实现
- 修复 stream 双向转发:任一方向完成立即关闭双端,避免连接泄漏
- 修复 SSL/TLS 中静默忽略错误的问题,添加日志记录
- 统一日志消息为英文

💘 Generated with Crush

Assisted-by: GLM 5.1 via Crush <crush@charm.land>
2026-04-28 18:00:48 +08:00
xfy
6f6a8f0455 refactor(adapter): 提取 HTTP/2/3 适配器公共逻辑为 CommonAdapter
将 http2 和 http3 适配器中重复的 sync.Pool 管理、流式请求体处理、
上下文重置等逻辑提取到 internal/adapter 包,通过 struct embedding 复用。
同时简化 ConnLimiter 直接实现 middleware.Middleware 接口,移除冗余 wrapper。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-28 17:06:41 +08:00
xfy
d191e1865d feat(static): 添加 expires 缓存控制支持
- StaticConfig 添加 Expires 字段,支持 nginx 兼容格式(30d, 1h, max, epoch)
- StaticHandler 添加 SetExpires 方法和缓存响应头设置
- serveFile 自动设置 Cache-Control 和 Expires 响应头
- nginx 转换器正确转换 expires 指令
- --generate-config 输出包含 expires 文档和示例

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 14:05:25 +08:00
xfy
07acfad146 feat(config): 添加 alias 配置支持
- StaticConfig 添加 Alias 字段,与 Root 互斥
- server.go 创建 handler 时设置 alias
- validate.go 添加 root/alias 互斥验证和路径安全检查
- converter.go nginx alias 指令正确转换为 Alias 字段
- defaults.go --generate-config 输出包含 alias 文档和示例

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-27 13:16:12 +08:00
xfy
1e38fe9e90 fix: 显式忽略不需要处理的错误返回值
对 os.Remove、conn.Close 等清理操作的返回值使用 _ 忽略,
避免 errcheck 静态检查告警。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-24 10:41:35 +08:00
xfy
00c5319819 refactor(proxy,server): 改进健康检查 goroutine 退出机制
- health: 使用 WaitGroup 确保 run goroutine 完全退出后再继续
- health_match: 忽略未使用参数,预分配 slice 容量
- proxy_coverage_extra_test: 使用 atomic.Int32 修复测试竞态条件
- purge: 忽略 Delete 返回值

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 13:35:03 +08:00
xfy
2bdc8f3b3b refactor(handler,middleware,server): 增强预压缩配置灵活性
- NewGzipStatic 增加 precompressedExtensions 参数,支持自定义预压缩扩展名
- SetGzipStatic 分离源文件扩展名和预压缩扩展名参数
- 更新相关测试用例

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 13:35:03 +08:00
xfy
9f7090df67 test(handler,middleware,server,ssl,proxy): 扩展测试覆盖率
- handler: 添加 sendfile 和 static 处理器测试
- middleware/security: 添加访问控制、认证、请求头、限流测试
- server: 添加池、pprof、清理、状态、升级、vhost 测试
- ssl: 添加客户端验证、OCSP、SSL 测试
- proxy: 添加代理覆盖率补充测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 10:42:05 +08:00
xfy
91f954936e refactor(server,middleware): 提取常量提高代码可读性
- ratelimit: 使用 accessUnknown 常量替代硬编码字符串
- testutil: 提取 testListenAddr 常量

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-22 10:41:48 +08:00
xfy
2b63666ea5 feat(proxy,server): 实现 ProxyBind/Buffering/ProxyURI 和响应头控制
ProxyBind 支持指定本地地址出站连接,Buffering 控制响应缓冲模式,
ProxyURI 实现 nginx proxy_pass URI 替换语义,
响应头新增 HideResponse/PassResponse/IgnoreHeaders/Cookie 域路径重写,
健康检查集成 RecordFailure/RecordSuccess 软失败状态。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 11:28:32 +08:00
xfy
7a96db9f05 test(server): 重构并扩展服务器测试
- 拆分 server_extended_test.go 到独立测试文件
- 添加 pprof、purge、vhost、internal 测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-21 08:12:33 +08:00
xfy
ae0bec6c3b feat(internal): 实现 internal 指令
- 新增 IsInternalRedirect 检测内部重定向请求
- static handler 支持 internal 访问限制
- proxy handler 支持 internal 访问限制
- 支持 X-Accel-Redirect 内部重定向

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 18:09:06 +08:00
xfy
3033d57764 feat(server): 实现 server_tokens 和 types 配置
- getServerName: 根据 ServerTokens 控制版本号显示
- applyTypesConfig: 应用自定义 MIME 类型配置
- 更新 location 添加方法调用

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 18:08:25 +08:00
xfy
2458ac1ed1 docs: 为其余模块添加标准化 godoc 注释
为剩余模块添加完整文档注释:
- app: 应用生命周期管理
- cache: 文件缓存
- config: 配置加载器
- handler: 静态文件处理和错误页面
- http2/http3: HTTP/2 和 HTTP/3 适配器
- loadbalance: 负载均衡算法和均衡器
- middleware: bodylimit、compression、rewrite、security
- mimeutil: MIME 类型检测
- netutil: URL 处理工具
- resolver: DNS 解析器
- server: 服务器升级处理
- ssl: SSL/TLS 和 OCSP
- stream: 流处理
- testutil: 测试工具
- variable: 变量池和 SSL 变量

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 10:59:53 +08:00
xfy
5f5717d6a4 test: 添加各模块覆盖率补充测试
- middleware/security: access 中间件覆盖率测试
- proxy: proxy 核心功能覆盖率测试
- server: server 扩展功能测试
- stream: stream 处理覆盖率测试

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 08:27:25 +08:00
xfy
28be9e7e66 fix(server): 添加 shutdownServers nil ctx 防御性检查
防止 ctx 参数为 nil 时导致 panic:
- nil ctx 时使用 context.Background() 作为默认值
- 防御性检查确保函数健壮性

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-20 08:26:51 +08:00
xfy
5a5f733cb4 refactor(logging): 将日志格式参数从布尔值改为字符串,支持 json/text/console 格式
将 Init 接口从 pretty bool 参数改为 format string 参数,
支持 json(纯 JSON)、text(无颜色 ConsoleWriter)、console(带颜色)三种格式。
简化 AppLogger 实现,统一使用 zerolog 格式化输出。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-17 17:26:08 +08:00
xfy
5f60dc9ff7 feat(server): 为静态文件处理添加符号链接安全检查
在 registerStaticHandlersWithLocationEngine 和 registerStaticHandlers
两个方法中设置 SymlinkCheck 安全检查,防止通过符号链接访问敏感文件。

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-17 10:41:13 +08:00
xfy
6281196dfd refactor(server): 优化结构体字段布局并使用 matcher 常量
- Server 和 VHostManager 结构体字段重新排序优化内存布局
- RegexHostMatcher 字段顺序调整
- 使用 matcher.LocationType* 常量替代硬编码字符串
- server_names 数组支持:遍历注册所有主机名
- 提取 createListener 方法支持 Unix socket

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-17 10:11:57 +08:00
xfy
c418baeb90 feat(vhost): 增强 server_name 匹配支持通配符和正则
按 nginx server_name 规则实现多类型匹配:
- 精确匹配:example.com
- 前缀通配:*.example.com(最长匹配优先)
- 后缀通配:example.*
- 正则匹配:~regex(按配置顺序)
- 匹配优先级:精确 → 前缀通配 → 后缀通配 → 正则 → 默认

更新 AddHost 返回 error 以支持正则编译错误反馈

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 09:26:47 +08:00
xfy
359afb5e24 feat(server): 集成 LocationEngine 和 Unix socket 监听支持
- 使用 LocationEngine 替代 fasthttp/router 进行路由匹配
- 新增 createListener 支持 Unix domain socket 监听
- 支持热升级场景下的 Unix socket 继承
- 新增 registerProxyRoutesWithLocationEngine 和 registerStaticHandlersWithLocationEngine
- 添加 SetUpgradeManager 方法供 App 层注入

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-17 09:26:38 +08:00