Skip to content

Instantly share code, notes, and snippets.

@seungjin
Created August 9, 2014 07:49
Show Gist options
  • Save seungjin/9ddf4fceb908ad7a50a2 to your computer and use it in GitHub Desktop.
Save seungjin/9ddf4fceb908ad7a50a2 to your computer and use it in GitHub Desktop.
//http://stackoverflow.com/questions/6564558/wildcards-in-the-pattern-for-http-handlefunc
/*
The patterns for http.Handler and http.HandleFunc aren't regular expressions or globs. There isn't a way to specify wildcards. They're documented here.
That said, it's not too hard to create your own handler that can use regular expressions or any other kind of pattern you want. Here's one that uses regular expressions (compiled, but not tested):
*/
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment