Gin: Reverse route generation

Created on 29 Jun 2015  路  16Comments  路  Source: gin-gonic/gin

I would like to help in adding the ability for routes to be named in the router and then reconstructed elsewhere in the application. One of the ways I was looking into doing this was to simply add named methods to the router.

router.NamedGET("show-user", "/users/:id", userShow)

The advantage to this would be to not change the return type of the router methods and lose chaining. The named routes could be added to the engine for access through the context.

func userShow(c *gin.Context) {
    url := c.Route("user-show").With(gin.Pair{"id": 44}).URL
    // or
    path := c.Route("user-show").With(gin.Pair{"id": 44}).Path
}

Does this seem in the scope of the framework? If so, what changes to the API would be welcomed to accomplish this?

Most helpful comment

@pior PR Welcome.

All 16 comments

@rafroehlich2 what is the use case of this?

@manucorporat The use case would be similar to the function of the Rails link helpers. When generating links in templates or JSON responses you can use the one provided to the router to keep them up to date. In a JSON server I built I use a similar method to handle HATEOAS.

@manucorporat :+1: would also like something like this for use in templates...

:+1:

+1

馃憤

+1 i really need this to set the location header on REST API responses

This is very useful for auto-generation of links in templates. I don't know if there's a workaround for this already but right now I have to hard code the link to my assets.

In Iris framework, all you have to do is

iris.Post("/users", UserHanlder).ChangeName("users")

or

iris.HandleFunc("POST", "/users", UserHandler)("users")

In Django, you do

url(r'^articles/([0-9]{4})/$', views.year_archive, name='news-year-archive'),

Just trying to prove that, certainly, there is a usecase for this.

+1, It will be easy to generate Restful Hypermedia API if here support this feature.

+1

+1

Is there any chance to get this feature to gin? cc @appleboy @austinheap @javierprovecho @thinkerou

Every services I've been working on has needed this at some point.
Definitely needed 馃憤

+1

This issue has not received much attention since 2015.
Is this a matter of developer bandwidth?
Would a PR implementing this be accepted? (assuming it would meet the expected code quality)

Ping @manucorporat @appleboy @javierprovecho @thinkerou

@pior PR Welcome.

Was this page helpful?
0 / 5 - 0 ratings