revel框架无内置全局http超时配置,须手动替换http.server并设readtimeout、writetimeout、idletimeout,同时在controller中用context.withtimeout控制业务逻辑,并同步配置nginx的proxy_connect_timeout、proxy_send_timeout和proxy_read_timeout。

Revel 应用自身不提供全局 HTTP 请求超时配置项
Revel 框架(截至 v1.1.0)没有像 Gin 的 gin.Engine.ReadTimeout 或 Echo 的 e.Server.ReadTimeout 那样内置的、可直接在配置文件或启动参数中设置的请求级超时字段。它默认使用 Go 标准库 net/http.Server,而超时控制必须落到该底层 Server 实例上——也就是说,你得自己接管 Server 启动逻辑,不能只依赖 revel.Run()。
必须手动替换默认 HTTP Server 并设置 ReadTimeout/WriteTimeout
Revel 默认调用的是内部封装的 http.ListenAndServe,无法注入自定义超时。要生效,必须在 app/init.go 中重写 revel.InterceptFunc 启动流程,并用带超时字段的 http.Server 替代默认行为。常见错误是只改了 handler 内部的 context.WithTimeout,但客户端早已断连,服务端还在读 body,导致 goroutine 泄漏。
-
ReadTimeout:从 TCP 连接建立到读完 request header 的最大耗时(含 TLS 握手),建议设为5 * time.Second -
WriteTimeout:从接收完整 request 到写出完整 response 的总耗时(含 handler 执行 + write header + write body),建议设为10 * time.Second -
IdleTimeout:keep-alive 连接空闲时间,避免连接长期挂起,推荐60 * time.Second
示例修改点(app/init.go):
func init() {
revel.InterceptFunc(beforeInit, revel.BEFORE_INIT)
}
<p>func beforeInit() {
// 替换默认 server 启动逻辑
revel.Server = &http.Server{
Addr: revel.HttpAddr,
Handler: revel.HTTPRouter,
ReadTimeout: 5 <em> time.Second,
WriteTimeout: 10 </em> time.Second,
IdleTimeout: 60 * time.Second,
}
}</p>
Handler 内部仍需用 context.WithTimeout 控制业务逻辑
Server 级超时只管连接生命周期,不管业务执行。比如一次 DB 查询卡住 8 秒,WriteTimeout 会兜底终止响应,但数据库连接可能已泄漏。所以每个 controller 方法里必须显式用 context.WithTimeout 包裹耗时操作,并确保调用链支持 context(如 db.QueryContext、http.Client.Do(req.WithContext(ctx)))。
- 不要传
r.Context()直接进子 goroutine——它会被 cancel 掉,且无法传递取消信号 - 避免用
time.AfterFunc模拟超时,它不中断底层 I/O,只是提前返回错误 - 第三方 SDK 若无
WithContext方法(如老版本redis-go),需自行加 channel + select 轮询ctx.Done()
Nginx 反向代理层也必须同步配置超时
生产环境 Revel 绝不直面公网,必然前置 Nginx。如果只设了 Revel 的 Server 超时,但 Nginx 的 proxy_read_timeout 是默认 60 秒,用户请求仍会在 Nginx 层卡满 60 秒才失败,完全绕过你的 Go 层超时控制。
必须在 Nginx 配置中显式对齐:
location / {
proxy_pass http://127.0.0.1:8089;
proxy_connect_timeout 5s;
proxy_send_timeout 10s;
proxy_read_timeout 10s; # 必须 ≤ WriteTimeout
proxy_http_version 1.1;
proxy_set_header Host $host;
}
最容易被忽略的是:Revel 的 session 依赖 X-Forwarded-Proto 头判断 HTTPS,若 Nginx 没传这个头,revel.Session().Get() 可能失效——超时没设对,session 先崩了。











