akko
akko

Reputation: 639

How to group routes in gin?

I want to group my routes in different files, so the main file won't be very messy.

I want something like this in their own files:

v1 := router.Group("/v1")
{
  v1.Group("users", usersRoutes)
  v1.Group("pictures", picturesRoutes)
  v1.Group("friends", friendsRoutes)
}

So each one of the *Routes would look something like this:

users := v1.Group("/users")
{
  users.GET("/", getUsers)
  users.POST("/", createUser)
}

Is this possible? Right now my code looks like this:

package app

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func getUrls() {
    v1 := router.Group("/v1")
    {
        ping := v1.Group("/ping")
        {
            ping.GET("/", pongFunction)
        }
        users := v1.Group("/users")
        {
            users.GET("/", getUsersFunction)
        }
    }
}

But this is going to increase its size a lot.

Upvotes: 13

Views: 25810

Answers (1)

Halil
Halil

Reputation: 2173

You would need to store router variable in your struct or global variable. Then individual go files will add handlers to that variable. Here is an example:

routes.go

package app

import (
    "github.com/gin-gonic/gin"
)

type routes struct {
    router *gin.Engine
}

func NewRoutes() routes {
    r := routes{
        router: gin.Default(),
    }

    v1 := r.router.Group("/v1")

    r.addPing(v1)
    r.addUsers(v1)

    return r
}

func (r routes) Run(addr ...string) error {
    return r.router.Run()
}

ping.go

package app

import "github.com/gin-gonic/gin"

func (r routes) addPing(rg *gin.RouterGroup) {
    ping := rg.Group("/ping")

    ping.GET("/", pongFunction)
}

func pongFunction(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "pong",
    })
}

users.go

package app

import "github.com/gin-gonic/gin"

func (r routes) addUsers(rg *gin.RouterGroup) {
    users := rg.Group("/users")

    users.GET("/", getUsersFunction)
}

func getUsersFunction(c *gin.Context) {
    c.JSON(200, gin.H{
        "users": "...",
    })
}

Upvotes: 19

Related Questions