如何在vercel无服务器功能中使用Go Gin ?



如何使单个文件处理vercel无服务器功能的所有路由?

默认情况下,它使用内置的处理程序,有没有办法使用gin模块来做同样的事情?

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!",
})
}

如果我正确理解了你的问题,你只需要创建struct Handler并创建一个方法"InitRoutes"返回带有所有handleFuncs的路由器

handleFuncs也应该是Handler

的方法例如:

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
}
之后你应该把它注入到httpServer中
srv := http.Server{
Addr:           ":" + port,
Handler:        Handler.InitRoutes(),
MaxHeaderBytes: 1 << 20,
ReadTimeout:    10 * time.Second,
WriteTimeout:   10 * time.Second,
}
srv.ListenAndServe()

最新更新