Accessing Requested URL Path Variables in Golang
In web applications, you may encounter scenarios where you need to read and utilize path variables from a requested URL that does not follow a predefined route pattern. This is a common requirement in dynamic websites that handle user input or data from external sources.
To achieve this in Golang, consider utilizing the gorilla/mux package, a popular router library that provides convenient mechanisms for handling and extracting path variables. Here's how you can implement it:
Install the gorilla/mux package:
<code class="go">import "github.com/gorilla/mux"</code>
Create a new router:
<code class="go">r := mux.NewRouter()</code>
Define a route handler:
<code class="go">handler := func(w http.ResponseWriter, r *http.Request) { // Extract the path parameter using the "Vars" map name := mux.Vars(r)["name"] fmt.Fprintf(w, "Hello, %s!", name) }</code>
Add the route to the router:
<code class="go">r.HandleFunc("/person/{name}", handler)</code>
In this example, we have defined a route that matches "/person/{name}", where "name" is a path parameter. The route handler function will be invoked whenever a request to this route is received. We then extract the "name" parameter from the request and display it as a greeting to the user.
Remember, in Gorilla/Mux, path variables are accessible through the Vars map associated with the request. You can specify the parameter names within curly braces in the route definition, and they will be available as keys in the Vars map to retrieve their values.
The above is the detailed content of How to Access Requested URL Path Variables in Golang Using Gorilla/Mux?. For more information, please follow other related articles on the PHP Chinese website!