Skip to content

Instantly share code, notes, and snippets.

@markbates
Created June 5, 2017 21:05
Show Gist options
  • Save markbates/f45c8c7bfb89671674d86ebc325d2afc to your computer and use it in GitHub Desktop.
Save markbates/f45c8c7bfb89671674d86ebc325d2afc to your computer and use it in GitHub Desktop.
package main
import (
"log"
"net/http"
"sync"
)
type Muxer struct {
routes map[string]http.Handler
moot *sync.Mutex
}
func (m Muxer) HandleFunc(pat string, h http.HandlerFunc) {
m.moot.Lock()
defer m.moot.Unlock()
m.routes[pat] = h
}
func (m Muxer) ServeHTTP(res http.ResponseWriter, req *http.Request) {
m.moot.Lock()
defer m.moot.Unlock()
if h, ok := m.routes[req.URL.Path]; ok {
log.Printf("%s\t%s\n", req.Method, req.URL.Path)
h.ServeHTTP(res, req)
return
}
log.Printf("[404] %s\t%s\n", req.Method, req.URL.Path)
http.NotFound(res, req)
}
func NewMuxer() Muxer {
return Muxer{
routes: map[string]http.Handler{},
moot: &sync.Mutex{},
}
}
func main() {
mux := NewMuxer()
mux.HandleFunc("/hello", func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("Hello, World!\n"))
})
mux.HandleFunc("/goodbye", func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("Goodbye, World!\n"))
})
http.ListenAndServe(":3000", mux)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment