dongling2545 2016-11-04 03:09
浏览 135
已采纳

我应该将goroutines与http.ListenAndServe一起使用吗?

If I'm using http.ListenAndServe to provide responses when the user hits a URL, should I be firing off the corresponding actions in the function as a goroutine ?

For instance, say I'm listening at /:

func main() {
    http.HandleFunc("/", provideMainContent)
}

func provideMainContent(w http.ResponseWriter, r *http.Request) {
    /// Bunch of code, looks up details in databases, parses, then returns
}

Should the bunch of code in provideMainContent be wrapped in a goroutine so it doesn't slow down any potential requests that come after the fact ?

  • 写回答

1条回答 默认 最新

  • douben8492 2016-11-04 06:34
    关注

    Short answer, No

    GoDoc from http.Serve :

    Serve accepts incoming HTTP connections on the listener l, creating a new service goroutine for each. The service goroutines read requests and then call handler to reply to them.

    However as mentioned in the question linked by @Mellow Marmot, there might be cases where you might want to spawn a goroutine to do some processing while you return from the handler so that the requester does not have to wait for all the processing to be done to get a response.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?