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
+10.1k Android Studio : Simple input textbox and intercept key example
+11.6k Golang : Convert decimal number(integer) to IPv4 address
+5.1k Javascript : Shuffle or randomize array example
+12.3k Golang : Add ASCII art to command line application launching process
+9.2k Golang : Convert(cast) string to int64
+20k Android Studio : AlertDialog and EditText to get user string input example
+6.9k Golang : Get environment variable
+13.5k Golang : Gin framework accept query string by post request example
+5.6k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+9.9k Golang : Text file editor (accept input from screen and save to file)
+9.8k Golang : Get login name from environment and prompt for password
+13.4k Golang : Tutorial on loading GOB and PEM files