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
+7.1k Golang : How to check if a string with spaces in between is numeric?
+4.9k Unix/Linux : Use netstat to find out IP addresses served by your website server
+9.7k Golang : Clean formatting/indenting or pretty print JSON result
+5.1k Golang : Example of how to detect which type of script a word belongs to
+3.6k Python : Create Whois client or function example
+10.9k Golang : error parsing regexp: invalid or unsupported Perl syntax
+28.5k Golang : Regular Expression for alphanumeric and underscore
+22k Golang : Get current file path of a file or executable
+18.7k Golang : How to get time zone and load different time zone?
+33.3k Golang : Convert to io.ReadSeeker type
+30.5k Golang : Validate IP address
+3.3k MariaDB/MySQL : Form select statement or search query with Chinese characters