回显上下文公开了HTTP请求,该请求已具有已绑定到服务器请求的上下文。只需获取该上下文,并检查其是否取消,和/或将其传递给采用上下文的方法。
ctx := c.Request().Context()select {case <-ctx.Done(): return ctx.Err()default: // Continue handling the request}// and pass along to the db or whatever else:rows, err := db.QueryContext(ctx, ...)如果客户端中止连接,则请求范围的上下文将自动取消。
如果您想添加自己的取消条件(超时或其他条件),也可以这样做:
req := c.Request()ctx, cancel := context.WithCancel(req.Context())req.WithContext(ctx)defer cancel()// do stuff, which may conditionally call cancel() to cancel the context early



