Skip to content

Commit

Permalink
Group example
Browse files Browse the repository at this point in the history
This example shows how to make a group of routes per file

This way we can create all routes of a certain topic in its own file so
the code will be cleaner

For example: All "/users" routes could be defined in users.go
  • Loading branch information
4k1k0 committed Jul 17, 2020
1 parent 63ea058 commit 176c0f1
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
10 changes: 10 additions & 0 deletions group-routes/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package main

import (
"github.com/gin-gonic/examples/group-routes/routes"
)

func main() {
// Our server will live in the routes package
routes.Run()
}
27 changes: 27 additions & 0 deletions group-routes/routes/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package routes

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

var (
router = gin.Default()
)

// Run will start the server
func Run() {
getRoutes()
router.Run(":5000")
}

// getRoutes will create our routes of our entire application
// this way every group of routes can be defined in their own file
// so this one won't be so messy
func getRoutes() {
v1 := router.Group("/v1")
addUserRoutes(v1)
addPingRoutes(v1)

v2 := router.Group("/v2")
addPingRoutes(v2)
}
15 changes: 15 additions & 0 deletions group-routes/routes/ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package routes

import (
"net/http"

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

func addPingRoutes(rg *gin.RouterGroup) {
ping := rg.Group("/ping")

ping.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "pong")
})
}
21 changes: 21 additions & 0 deletions group-routes/routes/users.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package routes

import (
"net/http"

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

func addUserRoutes(rg *gin.RouterGroup) {
users := rg.Group("/users")

users.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, "users")
})
users.GET("/comments", func(c *gin.Context) {
c.JSON(http.StatusOK, "users comments")
})
users.GET("/pictures", func(c *gin.Context) {
c.JSON(http.StatusOK, "users pictures")
})
}

0 comments on commit 176c0f1

Please sign in to comment.