Specifying Wildcards in Patterns for HTTP Handlers
When creating handlers using http.Handler or http.HandleFunc, you may want to specify wildcards in the pattern to match a range of URLs. Unfortunately, the patterns for these functions are not regular expressions and do not support wildcards by default.
Instead, you can create your own custom handler that supports pattern matching using regular expressions or any other desired pattern. Here's an example using regular expressions:
import ( "net/http" "regexp" ) type route struct { pattern *regexp.Regexp handler http.Handler } type RegexpHandler struct { routes []*route } func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) { h.routes = append(h.routes, &route{pattern, handler}) } func (h *RegexpHandler) HandleFunc(pattern *regexp.Regexp, handler func(http.ResponseWriter, *http.Request)) { h.routes = append(h.routes, &route{pattern, http.HandlerFunc(handler)}) } func (h *RegexpHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { for _, route := range h.routes { if route.pattern.MatchString(r.URL.Path) { route.handler.ServeHTTP(w, r) return } } // No pattern matched; send 404 response http.NotFound(w, r) }
By implementing your own custom handler, you gain the flexibility to define your own pattern matching logic and handle different types of URLs as needed.
The above is the detailed content of How Can I Match Wildcards in URL Patterns for HTTP Handlers?. For more information, please follow other related articles on the PHP Chinese website!