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 contentMost Helpful This Week
Regular expression to extract text between square brackets
How to convert Colorful PNG image to Gray-scale?
Strip all white spaces, tabs, newlines from a string
Find out how many logical processors used by current process
Higher Order Functions in Golang
How to use function from another file golang?