Using Regular Expressions for URL Pattern Matching in Go
Question:
How can I utilize regular expressions to determine the appropriate function for URL processing in a Go program?
Answer:
The provided code demonstrates the use of http.HandleFunc with a fixed path or rooted subtree. To use regular expressions for URL matching, register a handler to a rooted subtree and perform regexp matching within the handler.
Here's an example:
func main() { http.HandleFunc("/", route) // Match everything http.ListenAndServe(":8080", nil) } var rNum = regexp.MustCompile(`\d`) // Has digit(s) var rAbc = regexp.MustCompile(`abc`) // Contains "abc" 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")) }
Alternatively, consider using an external library such as Gorilla MUX for more flexibility in URL matching.
The above is the detailed content of How Can I Use Regular Expressions to Route URLs in Go?. For more information, please follow other related articles on the PHP Chinese website!