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

Create link with router #3256

Open asbjornu opened 2 years ago

asbjornu commented 2 years ago

Description

In this blog post, it is stated that the URL for a particular route can be created on the fly with the following method:

url := router.Url("homeHandler")

However, trying to access the Url method yields the following error:

router.Url undefined (type *gin.Engine has no field or method Url)

In what seems to be a fork of Gin 1.7.4, I've found the URLFor function, but I'm unable to find either the containing file template_func.go or the function URLFor in Gin's history. If anyone knows whether such a function has ever existed or something similar to it currently does exist, please shout!

How to reproduce

package main

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

func home(c *gin.Context) {
    router := gin.Default()
    url := router.Url("home")
    c.String(200, url)
}

func main() {
    router := gin.Default()
    router.GET("/", home)
    router.Run(":9000")
}

Expectations

Given a gin.Context, I expect to be able to construct a route URL on a whim, anywhere in my application.

Actual result

router.Url is not a method, so it fails:

router.Url undefined (type *gin.Engine has no field or method Url)

Environment

zy2324 commented 2 years ago

The blog is gin.New() , and you are only gin.Default(), I am not sure if it is affect or not

asbjornu commented 2 years ago

@zy2324, it doesn't affect which methods are available on the gin.Engine whether it's instantiated by gin.New() or gin.Default().