小智 6

BackgroundContextWithContextRequest
http.Handlerhttprouter.HandleRequest.Contextnil

要指定超时,请在您的处理程序中(就在“ //执行GET请求”注释的上方),您可以执行以下操作:

ctx, cancel := context.WithTimeout(r.Context(), time.Duration(60*time.Second))
defer cancel()
r = r.WithContext(ctx)

第一行创建了上下文并为您提供了取消钩子,您将其推迟;一旦处理了请求,则在执行此延迟调用(第2行)时,所有派生上下文(也就是添加变量的上下文)都将被取消。最后,第3行替换了请求,该请求现在包含更新的上下文。

ServeHTTP
type ContextKey string

const ContextUserKey ContextKey = "user"

// Then, just above your call to ServeHTTP...

ctx := context.WithValue(r.Context(), ContextUserKey, "theuser")
h.ServeHTTP(w, r.WithContext(ctx))

这会将现在两次派生的上下文(现在具有超时用户ID)传递给处理程序。

ValueContextinterface{}
user := r.Context().Value(ContextUserKey)
doSomethingForThisUser(user.(string))
cancel()