This tutorial help to understand golang regex router, I ll demostrate step by step process to achieve golang regex router.Golang doesn’t have built-in regex support for URL matching.It’s complicated to implement from scratch.The third party package or framework would be a better choice.
We ll use github.com/gorilla/mux package.Package gorilla/mux implements a request router and dispatcher for matching incoming requests to their respective handler.
func main() {
r := mux.NewRouter()
r.HandleFunc("/{name:pattern}", handle)
http.ListenAndServe(":8080", r)
}
where {name:pattern} could be simply {slug} (without pattern) or {id:[0-9]+} or combination of them /{employee}/{id:[0-9]+}, and the handler function is –
func handle(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
// for /{employee}/{id:[0-9]+} pattern
employee := params["employee"]
id := params["id"]
}
run it and try curl http://localhost:8080/employee/1
