gin icon indicating copy to clipboard operation
gin copied to clipboard

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

Open Orocker opened this issue 2 years ago • 1 comments

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

  • go version:1.21
  • gin version (or commit ref):v1.7.7
  • operating system:MacOS

Orocker avatar Dec 07 '23 08:12 Orocker

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

JimChenWYU avatar Aug 17 '24 10:08 JimChenWYU