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
Example: Split, Join, and Equal from BYTES Package
How to read current directory using Readdir?
Normal function parameter with variadic function parameter
Replace any non-alphanumeric character sequences with a dash using Regex
How to use function from another file golang?
How to fetch an Integer variable as String in Go?
How To Make an HTTP Server in Golang?
How to get the current date and time with timestamp in local and other timezones ?
How to copy a map to another map?
Various examples of printing and formatting in Golang