对于每个 API 请求,我是否应该使用 Fiber 运行一个 goroutine?

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

Should I run a goroutine for each api request using Fiber?

问题

所以我正在使用Fiber构建一个Rest API,我想知道是否应该在每个处理程序函数中运行goroutine。例如,假设我有以下路由:

router.Get("/get", getMockData)
router.Post("/create", createMockData)
router.Put("/update", updateMockData)
router.Delete("/delete", deleteMockData)

我应该将它们更改为以下形式吗:

// 我知道这在语法上不正确,但这只是一个例子。
router.Get("/get", go getMockData)
router.Post("/create", go createMockData)
router.Put("/update", go updateMockData)
router.Delete("/delete", go deleteMockData)

我应该这样做吗?我看过这个问题,它说不应该,但它针对的是net/http包,所以不太适用。

谢谢!

英文:

So I am using Fiber to build a Rest API and I was wondering on whether or not to run each handler function in a goroutine. For example, say I have the following routes:

router.Get("/get", getMockData)
router.Post("/create", createMockData)
router.Put("/update", updateMockData)
router.Delete("/delete", deleteMockData)

Should I change then to the following:

// I know this isn't syntactically correct but this is just an example. 
router.Get("/get", go getMockData)
router.Post("/create", go createMockData)
router.Put("/update", go updateMockData)
router.Delete("/delete", go deleteMockData)

Should I do this? I have looked at this question and it says no but its targeted towards the net/http package so it doesn't really apply.

Thank you!

答案1

得分: 1

不。你不能将函数作为goroutine传递,因为这在概念上是错误的。在router.Get("/get", getMockData)中,你传递的是一个函数的引用,其中getMockData是一个函数的引用。你没有调用该函数,因为这不是你的责任。这是Fiber或你使用的任何其他REST框架的责任。当客户端访问像/get这样的API时,Fiber会调用该函数,并且很可能在一个单独的goroutine中以提高效率。

英文:

No. You can't pass a function as a goroutine as this is conceptually wrong. You are passing a reference to a function in router.Get("/get", getMockData) where getMockData is a reference of a function. You are not calling that function as this is not your responsibility. It's the responsibility of Fiber or whatever rest framework you use. When a client hit a API like /get Fiber will call that function and most probably in a separate goroutine for efficiency.

huangapple
  • 本文由 发表于 2023年1月17日 06:22:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75140252.html
匿名

发表评论

匿名网友

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

确定