GoLang简单的REST API应该使用Go协程(GoRoutines)。

huangapple go评论94阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年3月7日 18:38:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/22247773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定