gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:19:43 31 4
gpt4 key购买 nike

如果我使用 http.ListenAndServe 在用户点击 URL 时提供响应,我是否应该将函数中的相应操作作为 goroutine 触发?

例如,假设我正在听 /:

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

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

是否应该将 provideMainContent 中的一堆代码包装在一个 goroutine 中,这样它就不会减慢事后发生的任何潜在请求?

最佳答案

简答,否

来自 http.Serve 的 GoDoc:

Serve 在监听器 l 上接受传入的 HTTP 连接,为每个连接创建一个新的服务 goroutine。服务 goroutine 读取请求,然后调用处理程序回复它们。

然而,正如 @Mellow Marmot 链接的问题中提到的,在某些情况下,您可能希望在从处理程序返回时生成一个 goroutine 来执行一些处理,这样请求者就不会必须等待所有处理完成才能获得响应。

关于go - 我应该将 goroutines 与 http.ListenAndServe 一起使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414685/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com