英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论