Bootstrap

标题:上下文超时限制

分类:默认分类, 创建日期:2026-01-01 04:21:58, 更新日期:2026-01-01 04:21:58, 阅读次数:500

优化 1:客户端断开时主动退出主循环(已在代码中实现,确认即可)

你的sseHandler中已通过<-r.Context().Done()监听客户端断开,会触发主循环退出,goroutine 自动回收,无需修改。

优化 2:限制 SSE 连接的空闲超时(可选,避免客户端异常断开导致 goroutine 残留)

在sseHandler开头增加空闲超时配置(比如 5 分钟),即使客户端异常断开,也能自动回收 goroutine:

func sseHandler(w http.ResponseWriter, r *http.Request) {
	// 新增:设置SSE连接空闲超时(5分钟)
	ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute)
	defer cancel()
	r = r.WithContext(ctx) // 替换请求上下文

	// 原有逻辑...
	// 1. 并发限制
	// 2. 设置响应头
	// ...
}

四、总结


堆栈条目关联 SSE是否正常优化建议
sseHandler(2 个)正常可选增加空闲超时
setupShutdown(1 个)正常无需修改
HTTP/TLS 读写(9 个)正常属于 Go HTTP 底层,无需处理
Server_info(2 个)正常无关,可忽略
pprof(1 个)正常无关,可忽略

你的 SSE 代码逻辑无异常 goroutine 泄漏,当前的 goroutine 数量是业务正常运行的表现,无需担心资源问题。如果后续发现sseHandler的 goroutine 数量远大于实际客户端数,再补充 “空闲超时” 优化即可。

Server Information

This is a wider card with supporting text below as a natural lead-in to additional content.

Redis Information

This is a wider card with supporting text below as a natural lead-in to additional content.

Go Gopher climbing a ladder.