英文:
How to use Go Gin in vercel serveless functions?
问题
如何创建一个单个文件来处理 Vercel 无服务器函数的所有路由?
默认情况下,它使用内置的处理程序,是否有办法使用 gin 模块来完成相同的功能?
package handler
import "github.com/gin-gonic/gin"
/* 获取 post 数据并将相同的数据作为响应发送 */
func Hi(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello World!",
})
}
英文:
How to make a single file to handle all the routes for the vercel serverless function?
By default it uses the inbuilt handler is there any way to use the gin module to do the same ?
package handler
import "github.com/gin-gonic/gin"
/* get the post data and send the same data as response */
func Hi(c *gin.Context) {
c.JSON(200, gin.H{
"message": "Hello World!",
})
}
</details>
# 答案1
**得分**: 1
如果我正确理解了你的问题,你只需要创建一个名为"Handler"的结构体,并创建一个名为"InitRoutes"的方法,该方法返回一个包含所有handleFunc的路由器。
handleFunc也应该是Handler的方法。
例如:
```go
type Handler struct {
// 在这里你可以注入服务
}
func NewHandler(services *service.Service) *Handler {
return &Handler{}
}
func (h *Handler) InitRoutes() *gin.Engine {
router := gin.New()
auth := router.Group("/group")
{
auth.POST("/path", h.handleFunc)
auth.POST("/path", h.handleFunc)
}
return router
}
之后,你应该将其注入到你的httpServer中:
srv := http.Server{
Addr: ":" + port,
Handler: Handler.InitRoutes(),
MaxHeaderBytes: 1 << 20,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
srv.ListenAndServe()
英文:
If I correctly understood your question, you just need to create struct Handler and make a method "InitRoutes" returning router with all handleFuncs
handleFuncs also should be methods of Handler
For example:
type Handler struct {
// here you can inject services
}
func NewHandler(services *service.Service) *Handler {
return &Handler{}
}
func (h *Handler) InitRoutes() *gin.Engine {
router := gin.New()
auth := router.Group("/group")
{
auth.POST("/path", h.handleFunc)
auth.POST("/path", h.handleFunc)
}
return router
}
After that you should inject it into your httpServer
srv := http.Server{
Addr: ":" + port,
Handler: Handler.InitRoutes(),
MaxHeaderBytes: 1 << 20,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
}
srv.ListenAndServe()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论