How to use wildcard or a variable in our URL for complex routing?

From Gorilla web toolkit the gorilla/mux is used to create flexible routes that allow regular expressions to dictate available variables for routers.

The following source code snippet shows an abbreviated program with a (very basic) regular expression in the handler.
We're assigning any number of digits after /pages/ to a parameter named id in {id:[0-9]+}.This is the value we determine in pageHandler.
1.html: <html> <head> <title>Golang Template Example</title> </head> <body> <h1>ONE</h1> </body> </html>
package main
import (
  "github.com/gorilla/mux"
  "net/http"    
)
const (
  PORT = ":8080"
)
func pageHandler(w http.ResponseWriter, r *http.Request) {
  vars := mux.Vars(r)
  varId := vars["id"]  
  fileName := varId + ".html"  
  http.ServeFile(w,r,fileName)
}
func main() {
  rtr := mux.NewRouter()
  rtr.HandleFunc("/number/{id:[0-9]+}", pageHandler)  
  http.Handle("/", rtr)
  http.ListenAndServe(PORT, nil)
}


Now run url http://localhost:8080/number/1 in your browser and see the below content

Thanks for reading. Please leave your valuable feedback and comments.

* Required Fields

No questions yet. Be the first to ask the question!