Home > Article > Backend Development > How Can I Use Regular Expressions for Flexible URL Routing in Go?
Using Regular Expressions to Map URLs in Go
In Go, using regular expressions to match URLs allows for more flexible and expressive URL routing. However, relying on the http.HandleFunc() function for this purpose is not ideal.
The http.HandleFunc() function is primarily intended for matching fixed paths or rooted subtrees. It does not support the use of regular expressions. To achieve that, you need to register a handler to a rooted subtree (e.g., /), and then implement custom regexp matching and routing within the handler.
Consider the following example:
import ( "fmt" "net/http" "regexp" ) var rNum = regexp.MustCompile(`\d`) // Matches URLs with digits var rAbc = regexp.MustCompile(`abc`) // Matches URLs containing "abc" func main() { http.HandleFunc("/", route) http.ListenAndServe(":8080", nil) } func route(w http.ResponseWriter, r *http.Request) { switch { case rNum.MatchString(r.URL.Path): digits(w, r) case rAbc.MatchString(r.URL.Path): abc(w, r) default: w.Write([]byte("Unknown Pattern")) } } func digits(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Has digits")) } func abc(w http.ResponseWriter, r *http.Request) { w.Write([]byte("Has abc")) }
This code:
Alternatively, you can utilize external libraries like Gorilla MUX to achieve more advanced and versatile URL routing capabilities.
The above is the detailed content of How Can I Use Regular Expressions for Flexible URL Routing in Go?. For more information, please follow other related articles on the PHP Chinese website!