如何在 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!",

    })

}


慕娘9325324
浏览 210回答 1
1回答

慕容3067478

如果我正确理解了你的问题,你只需要创建 struct Handler 并创建一个方法“InitRoutes”返回带有所有 handleFuncs 的路由器handleFuncs 也应该是 Handler 的方法例如:type Handler struct {&nbsp; &nbsp; // here you can inject services}func NewHandler(services *service.Service) *Handler {&nbsp; &nbsp; return &Handler{}}func (h *Handler) InitRoutes() *gin.Engine {&nbsp; &nbsp; router := gin.New()&nbsp; &nbsp; auth := router.Group("/group")&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; auth.POST("/path", h.handleFunc)&nbsp; &nbsp; &nbsp; &nbsp; auth.POST("/path", h.handleFunc)&nbsp; &nbsp; }&nbsp; &nbsp; return router}之后你应该将它注入你的 httpServersrv := http.Server{&nbsp; &nbsp; &nbsp; &nbsp; Addr:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;":" + port,&nbsp; &nbsp; &nbsp; &nbsp; Handler:&nbsp; &nbsp; &nbsp; &nbsp; Handler.InitRoutes(),&nbsp; &nbsp; &nbsp; &nbsp; MaxHeaderBytes: 1 << 20,&nbsp; &nbsp; &nbsp; &nbsp; ReadTimeout:&nbsp; &nbsp; 10 * time.Second,&nbsp; &nbsp; &nbsp; &nbsp; WriteTimeout:&nbsp; &nbsp;10 * time.Second,&nbsp; &nbsp; }srv.ListenAndServe()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go