Home >Backend Development >Golang >How to Handle Arbitrary URL Paths in Go Without Predefined Routes?
Customizing URL Routing in Go
When building web applications in Go, it's common to define predefined routes for specific URLs. However, there are instances where you may need to read and handle arbitrary URL paths without predetermined routes.
Reading and Printing Parameters from a Dynamic URL
To read the "any_name" parameter from a URL path like "example.com/person/(any_name)", consider using the popular gorilla/mux package. Here's how you can implement it:
<code class="go">import ( "fmt" "net/http" "github.com/gorilla/mux" ) func main() { // Create a new router r := mux.NewRouter() // Define a route handler for the dynamic URL pattern r.HandleFunc("/person/{name}", func(w http.ResponseWriter, r *http.Request) { // Get the "name" parameter from the URL vars := mux.Vars(r) name := vars["name"] // Print the name to the response fmt.Fprintf(w, "Hello, %s!", name) }) // Start the HTTP server http.ListenAndServe(":8080", r) }</code>
How it Works
The above is the detailed content of How to Handle Arbitrary URL Paths in Go Without Predefined Routes?. For more information, please follow other related articles on the PHP Chinese website!