Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Last active December 14, 2015 15:48
Show Gist options
  • Save kylelemons/5110100 to your computer and use it in GitHub Desktop.
Save kylelemons/5110100 to your computer and use it in GitHub Desktop.
Straw man case-insensitive serve mux
package main
import "net/http"
import pathpkg "path"
import "strings"
type InsensitiveMux struct {
handlers map[string]http.Handler
isDir map[string]bool
}
func (m *InsensitiveMux) Handle(path string, handler http.Handler) {
if m.handlers == nil {
m.handlers = map[string]http.Handler{}
}
if path[0] != '/' {
panic("invalid path")
}
dir := path[len(path)-1] == '/'
path = pathpkg.Clean(path)
m.handlers[path] = handler
m.isDir[path] = dir
}
func (m *InsensitiveMux) HandleFunc(path string, f func(w http.ResponseWriter, r *http.Request)) {
m.Handle(path, http.HandlerFunc(f))
}
func (m *InsensitiveMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
// Try case sensitive
var best = m.handlers["/"]
for i, r := range path {
if r != '/' {
continue
}
if h, ok := m.handlers[path[:i]]; ok {
best = h
}
}
if best != nil {
best.ServeHTTP(w, r)
return
}
// Try case insensitive
path = strings.ToLower(path)
for i, r := range path {
if r != '/' {
continue
}
if h, ok := m.handlers[path[:i]]; ok {
best = h
}
}
if best != nil {
http.Redirect(w, r, path, http.StatusMovedPermanently)
return
}
http.NotFound(w, r)
}
func main() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment