将上下文添加到现有的 http 处理程序函数

我必须遵循设置。我有一个多路复用 HTTP 服务器,我想向其添加上下文以提高弹性。


srv := http.Server{

    Addr:         ":" + _operatorPortStr,

    WriteTimeout: 8 * time.Second,

    Handler:      http.TimeoutHandler(router, 5*time.Second, "Timeout!\n"),

}

srv.ListenAndServe()

我现在有了我的处理函数,如果 HTTP 请求达到超时,我想终止它。


func Deploy(w http.ResponseWriter, r *http.Request) {


loadConfigs()


calltos3()


updateResource()


}

主要问题是不可能将上下文传递给每个函数,因为它们的级别非常高。那么在超时后向处理程序添加上下文以终止请求的正确方法是什么?


缥缈止盈
浏览 133回答 1
1回答

叮当猫咪

超时处理程序在请求中设置上下文。您可以使用请求上下文来检查请求是否超时:func Deploy(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp;...&nbsp; &nbsp;select {&nbsp; &nbsp; &nbsp; case <-r.Context().Done():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// Timed out&nbsp; &nbsp; &nbsp; default:&nbsp; &nbsp;}&nbsp; &nbsp;...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go