How to Structure Your Gin Routes for Clean Code?

Linda Hamilton
Release: 2024-11-02 21:09:02
Original
642 people have browsed it

How to Structure Your Gin Routes for Clean Code?

Grouping Routes in Gin for Clean Code

Organizing routes into separate files is a common practice to reduce the clutter and complexity of a main router file. In Gin, this can be achieved by leveraging the Group method.

One approach is to store the router variable as a struct member or global variable, allowing individual files to add handlers to it. Here's an example:

routes.go

<code class="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()
}</code>
Copy after login

ping.go

<code class="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",
    })
}</code>
Copy after login

users.go

<code class="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": "...",
    })
}</code>
Copy after login

By utilizing this approach, each function file can define handlers within its specific group, keeping the main codebase organized and modular.

The above is the detailed content of How to Structure Your Gin Routes for Clean Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!