Adithya Pai B
Adithya Pai B

Reputation: 13

How to use Go Gin in vercel serveless functions?

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

Upvotes: 1

Views: 1250

Answers (1)

Limmperhaven
Limmperhaven

Reputation: 62

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()

Upvotes: 1

Related Questions