Matching URLs with Regular Expressions in Go
In Go, http.HandleFunc() is designed to handle specific URL patterns. However, it's not suitable for matching patterns using regular expressions.
Alternative Solutions:
Instead, consider the following solutions:
// Match everything http.HandleFunc("/", route) var rNum = regexp.MustCompile(`\d`) // Has digit(s) func route(w http.ResponseWriter, r *http.Request) { if rNum.MatchString(r.URL.Path) { digits(w, r) } else { w.Write([]byte("No digits found")) } }
For example, with Gorilla MUX:
r := mux.NewRouter() r.HandleFunc("/digits", digitsHandler).Methods("GET") r.HandleFunc("/abc", abcHandler).Methods("POST") http.Handle("/", r)
Each of these methods allows for more detailed URL matching based on specific requirements.
The above is the detailed content of How to Match URLs with Regular Expressions in Go?. For more information, please follow other related articles on the PHP Chinese website!