Created
June 5, 2017 21:05
-
-
Save markbates/f45c8c7bfb89671674d86ebc325d2afc to your computer and use it in GitHub Desktop.
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 ( | |
"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