生产环境血泪史

某支付系统因Context未正确传递导致千万级资金滞留

// 陷阱1:time.After未关闭
select {
case <-ctx.Done():

return

case <-time.After(10*time.Second):

// 资源持续泄漏!

}

// 陷阱2:WithCancel未调用cancel
ctx, cancel := context.WithCancel(parent)
// 忘记defer cancel() → goroutine永不回收

// 陷阱3:HTTP请求未传递Context
client.Do(req) // 应使用 client.Do(req.WithContext(ctx))

正确模式

// 超时控制三要素
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel() // 必须确保调用

req = req.WithContext(ctx)
client.Do(req)

内存泄漏证据

方案Goroutine数量内存增长
陷阱21,200+4.2GB/h
修复后12稳定0.8GB