Reading URL Path Parameters in Go
You are developing a web application in Go that requires handling specific URL paths. In particular, you want to read and display a portion of a URL path in the format example.com/person/(any_name), where (any_name) represents a variable parameter.
To accomplish this, the gorilla/mux package is highly recommended for route handling.
Using gorilla/mux
The gorilla/mux package is a powerful router for Go. It provides a straightforward way to define and manage routes, including the ability to capture parameters from URLs.
Here's how you can use gorilla/mux to read and print the (any_name) parameter:
<code class="go">package main import ( "fmt" "log" "net/http" "github.com/gorilla/mux" ) func PersonHandler(w http.ResponseWriter, r *http.Request) { vars := mux.Vars(r) name := vars["name"] fmt.Fprintf(w, "Hello, %s!", name) } func main() { r := mux.NewRouter() r.HandleFunc("/person/{name}", PersonHandler).Methods(http.MethodGet) if err := http.ListenAndServe(":8080", r); err != nil { log.Fatal(err) } }</code>
In this script, we:
When a request is made to example.com/person/John, the PersonHandler function will be invoked with the parameter name set to John. The function will then print "Hello, John!" to the response.
The above is the detailed content of How to Extract URL Path Parameters Using Gorilla/Mux in Go?. For more information, please follow other related articles on the PHP Chinese website!