func handler(c *gin.Context) {
// 创建一个具有超时的上下文
ctx, cancel := context.WithTimeout(c, 5*time.Second)
defer cancel() // 确保在函数退出时调用 cancel,释放资源
// 使用协程执行处理逻辑
done := make(chan struct{})
go func() {
defer close(done)
// 模拟长时间运行的处理过程
time.Sleep(10 * time.Second)
}()
// 等待处理逻辑执行完毕或超时
select {
case <-done:
/// 继续正常处理
c.JSON(http.StatusOK, gin.H{"message": "处理完成"})
case <-ctx.Done():
// 如果超时发生,则上下文被取消
fmt.Println("处理超时:", ctx.Err())
c.JSON(http.StatusRequestTimeout, gin.H{"error": "处理超时"})
}
}
func main() {
// 创建一个 Gin 引擎
router := gin.Default()
// 定义一个处理器函数
router.GET("/", handler)
// 启动 HTTP 服务器
router.Run(":8080")
}