-
Notifications
You must be signed in to change notification settings - Fork 0
Stripped-down http.ServeMux with Regular Expressions and Mount
License
touchmarine/mux
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
= Mux
Package mux is a stripped-down http.ServeMux with a few select extras like
regular expression patterns and mounting.
- mux supports only http.HandlerFunc, http.Handler is not supported
- non-regexp handler pattern must begin with a slash "/" and must not end with
a slash "/"
- requests with a trailing slash are redirected to the slash-less version
- mux is case-sensitive; for case-insensitive matching, look at the case-insensitive example
## Examples
+ Basic
``go
m := mux.New(http.NotFound)
m.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello")
})
http.ListenAndServe(":8080", m)
``
+ Regular expression patterns
``go
m := mux.New(http.NotFound)
m.RegexpHandleFunc(`/users/(?P<id>[0-9]+)$`, func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.Context().Value("id").(string))
if err != nil {
w.WriteHeader(http.StatusUnprocessableEntity)
return
}
fmt.Fprintf(w, "id=%d", id)
// ...
})
``
+ Mount
``go
mu := mux.New(http.NotFound)
mu.HandleFunc("/report", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "user report")
})
m := mux.New(http.NotFound)
m.Mount("/users", mu)
http.ListenAndServe(":8080", m)
``
+ Case-insensitive
``go
func caseInsensitive(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.ToLower(r.URL.Path)
handler.ServeHTTP(w, r)
}
}
m := mux.New(http.NotFound)
m.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "hello")
})
http.ListenAndServe(":8080", caseInsensitive(m))
``
About
Stripped-down http.ServeMux with Regular Expressions and Mount
Resources
License
Stars
Watchers
Forks
Packages 0
No packages published