为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
慕娘9325324 2022-12-13 11:13:45
如何制作一个文件来处理 vercel 无服务器功能的所有路由?默认情况下它使用内置处理程序有没有办法使用 gin 模块来做同样的事情?package handlerimport "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!",    })}
查看完整描述

1 回答

?
慕容3067478

TA贡献1773条经验 获得超3个赞

如果我正确理解了你的问题,你只需要创建 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()


查看完整回答
反对 回复 2022-12-13
  • 1 回答
  • 0 关注
  • 209 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号