gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
77.95k stars 7.97k forks source link

How to add a name to the gin route like laravel? #3795

Open Orocker opened 9 months ago

Orocker commented 9 months ago

Description

Question detail:https://stackoverflow.com/questions/77618417/how-to-add-a-name-to-the-gin-route-like-laravel

I want to add a name to the gin route because I need to collect all the routes and display them on the page.

package main

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

func main() {
    r := gin.Default()
    r.GET("/api/user/list", handler1,"Get User List")
    r.POST("/api/user/create",handle2,"Create an User")         
}

Expectations


## Actual result

Environment

JimChenWYU commented 4 weeks ago

I want to add a name to the gin route because I need to collect all the routes and display them on the page.

maybe help you.

package main

import (
    "net/http"

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

func main() {
    r := gin.Default()

    var routes gin.RoutesInfo
    r.POST("/upload", func(c *gin.Context) {
        c.String(http.StatusOK, "OK")
    })
    r.GET("/user/:id", func(c *gin.Context) {
        c.String(http.StatusOK, "OK")
    })
    r.GET("/routes", func(c *gin.Context) {
        type Route struct {
            Method  string `json:"method"`
            Path    string `json:"path"`
            Handler string `json:"handler"`
        }
        data := make([]Route, 0, len(routes))
        for _, route := range routes {
            data = append(data, Route{
                Method:  route.Method,
                Path:    route.Path,
                Handler: route.Handler,
            })
        }
        c.JSON(200, data)
    })

    routes = r.Routes()
    _ = r.Run(":8080")
}