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
+4.8k Golang : Frobnicate or tweaking a string example
+7.7k Python : Fix SyntaxError: Non-ASCII character in file, but no encoding declared
+12.5k Golang : Read from buffered reader until specific number of bytes
+4.9k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+21.1k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+28.5k Golang : Get time.Duration in year, month, week or day
+15.1k Golang : Get sub string example
+9.1k Golang : Setting variable value with ldflags
+24.1k Golang : Get current file path of a file or executable
+9.2k Golang : Print how to use flag for your application example
+14k Golang : Basic authentication with .htpasswd file
+24.9k Golang : Get executable name behind process ID example