Golang : Gorrila set route name and get the current route name
Problem :
You want to know the current route that your user is using on your website and retrieve the name of the route. How to that with Gorrilla Web toolkit ?
Solution :
Before you can get the name of the route, first you need to give it a name.
For example :
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld)
to
mx := mux.NewRouter()
mx.HandleFunc("/", SayHelloWorld).Name("home") // route named home
Next, get the current route from the user request(r *http.Request) and get the route name with GetName()
function.
func SayHelloWorld(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
route := mux.CurrentRoute(r)
w.Write([]byte(fmt.Sprintf("Route name is %v ", route.GetName())))
}
Knowing the route name is useful in situation where you need to build URL. For example, to redirect user to the newly built URL.
References :
See also : Golang : Gorilla mux routing example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.4k Golang : Convert spaces to tabs and back to spaces example
+21.7k Golang : Gorilla mux routing example
+19.1k Golang : How to force compile or remove object files first before rebuild?
+17.2k Golang : Send email with attachment
+29.2k Golang : Interpolating or substituting variables in string examples
+18.5k Golang : How to get time from unix nano example
+5k Golang : Shuffle array of list
+33.5k Golang : Upload and download file to/from AWS S3
+6.3k Golang : File system scanning
+14.6k Golang : Update database with GORM example
+16.2k Golang : Clone with pointer and modify value
+7.9k Golang : HTTP Routing with Goji example