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
+35.9k Golang : Get file last modified date and time
+7.8k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+22.1k Golang : How to run Golang application such as web server in the background or as daemon?
+21.6k SSL : How to check if current certificate is sha1 or sha2
+16.7k Golang : Read integer from file into array
+9.3k Golang : Create unique title slugs example
+11k Golang : Fix go.exe is not compatible with the version of Windows you're running
+12.6k Golang : Send data to /dev/null a.k.a blackhole with ioutil.Discard
+7.8k Javascript : How to check a browser's Do Not Track status?
+14.5k Golang : How to get URL port?
+7.5k Golang : Shuffle strings array
+9k Golang : How to capture return values from goroutines?