How to use Go Gin in vercel serveless functions?

huangapple go评论77阅读模式
英文:

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 &amp;Handler{}
}

func (h *Handler) InitRoutes() *gin.Engine {
    router := gin.New()

    auth := router.Group(&quot;/group&quot;)
    {
	    auth.POST(&quot;/path&quot;, h.handleFunc)
	    auth.POST(&quot;/path&quot;, h.handleFunc)
    }

    return router
}

After that you should inject it into your httpServer

srv := http.Server{
	    Addr:           &quot;:&quot; + port,
	    Handler:        Handler.InitRoutes(),
	    MaxHeaderBytes: 1 &lt;&lt; 20,
	    ReadTimeout:    10 * time.Second,
	    WriteTimeout:   10 * time.Second,
    }

srv.ListenAndServe()

huangapple
  • 本文由 发表于 2022年5月11日 22:39:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/72203014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定