英文:
GoLang simple REST API should use GoRoutines
问题
我的问题非常简单。
对于一个非常简单的REST API,我应该使用GoRoutines吗?
我基本上只是对数据库进行简单的查询,验证会话或进行登录。这些操作中的任何一个值得设置一个GoRoutine吗?什么时候使用GoRoutines是有用的,如何设置它们?
英文:
My question is very simple.
Should I make use of GoRoutines for a very simple REST API?
I basically only do simple queries to a DB, verify sessions, or do logins. Is any of this operations worth setting up a GoRoutine? When are GoRoutines useful, and how should I set them up?
答案1
得分: 22
net/http
包已经为你处理了这个问题。一旦你调用Serve
(或更常见的是ListenAndServe
),以下操作将会发生:
> Serve在监听器l上接受传入的HTTP连接,为每个连接创建一个新的服务goroutine。服务goroutine读取请求,然后调用处理程序来回复请求。处理程序通常为nil,此时会使用DefaultServeMux。
更多信息请参考http://golang.org/pkg/net/http/。
如果一个请求触发了需要较长处理时间的情况,并且你不想让客户端等待,你可能需要另一个goroutine。
英文:
The net/http
package already takes care of this for you. Once you call Serve
(or more likely ListenAndServe
) the following happens:
> 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. Handler is typically nil, in which case the DefaultServeMux is used.
See http://golang.org/pkg/net/http/ for more.
You may want another goroutine if a request triggers the need for longer processing and you don't want to make the client wait.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论