Fix the HostSwitch example
Thanks to Tobias Schwarz for reporting problems!
diff --git a/README.md b/README.md
index 9e28d50..03b7f0f 100644
--- a/README.md
+++ b/README.md
@@ -131,32 +131,33 @@
```go
// We need an object that implements the http.Handler interface.
// Therefore we need a type for which we implement the ServeHTTP method.
-// We just use a map here, in which we map host names to http.Handlers
+// We just use a map here, in which we map host names (with port) to http.Handlers
type HostSwitch map[string]http.Handler
// Implement the ServerHTTP method on our new type
func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Check if a http.Handler is registered for the given host.
// If yes, use it to handle the request.
- if handler := hs[r.URL.Host]; handler != nil {
+ if handler := hs[r.Host]; handler != nil {
handler.ServeHTTP(w, r)
+ } else {
+ // Handle host names for wich no handler is registered
+ http.Error(w, "Forbidden", 403) // Or Redirect?
}
-
- // Handle host names for wich no handler is registered
- http.Error(w, "Forbidden", 403) // Or Redirect?
}
func main() {
// Initialze a router as usual
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/hello/:name", Hello)
+ router := httprouter.New()
+ router.GET("/", Index)
+ router.GET("/hello/:name", Hello)
- // Make a new HostSwitch and insert the router for example.com
- hs := make(HostSwitch)
- hs["example.com"] = router
+ // Make a new HostSwitch and insert the router (our http handler)
+ // for example.com and port 12345
+ hs := make(HostSwitch)
+ hs["example.com:12345"] = router
- // Use the HostSwitch to listen and serve on port 12345
- log.Fatal(http.ListenAndServe(":12345", hs))
+ // Use the HostSwitch to listen and serve on port 12345
+ log.Fatal(http.ListenAndServe(":12345", hs))
}
```