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: Golang Template Example

ONE

Example


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

Most Helpful This Week