Created
August 22, 2019 19:43
Star
You must be signed in to star a gist
Go web server example with support for URL matching on regular expressions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"regexp" | |
) | |
type route struct { | |
pattern *regexp.Regexp | |
handler http.Handler | |
} | |
// RegexpHandler bla bla | |
type RegexpHandler struct { | |
routes []*route | |
} | |
// Handler bla bla | |
func (h *RegexpHandler) Handler(pattern *regexp.Regexp, handler http.Handler) { | |
h.routes = append(h.routes, &route{pattern, handler}) | |
} | |
// HandleFunc bla bla | |
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) | |
} | |
func handleDigits(res http.ResponseWriter, req *http.Request) { | |
res.Write([]byte("Digits in the URL\n")) | |
} | |
func handleStrings(res http.ResponseWriter, req *http.Request) { | |
res.Write([]byte("Strings in the URL\n")) | |
} | |
func main() { | |
handler := &RegexpHandler{} | |
reg1, _ := regexp.Compile("/foo-\\d+") | |
handler.HandleFunc(reg1, handleDigits) | |
reg2, _ := regexp.Compile("/foo-\\w+") | |
handler.HandleFunc(reg2, handleStrings) | |
http.ListenAndServe(":3000", handler) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment