canonical host

This commit is contained in:
Mark McGranaghan 2012-09-19 22:00:15 -07:00
parent b71b350973
commit 0f2d408137
3 changed files with 41 additions and 1 deletions

5
README
View File

@ -43,7 +43,6 @@ gobyexample.com signups
* return status code
* serve static files
* force https
* force canonical host
* not found page
* error page
* string formatting
@ -66,6 +65,10 @@ gobyexample.com signups
* init functions
* using gofmt
* scrolls style logging
* range and close http://tour.golang.org/#66
* string replacement - sub & gsub
* benchmarking
* profiling
* setting up go env, hello world
* deploying to heroku

View File

@ -33,3 +33,6 @@ func main() {
rectangle := Rectangle {x1: 3, x2: 10, y1: 5, y2: 7}
fmt.Println(rectangle.area())
}
// == todo
// pointer vs value receivers

View File

@ -0,0 +1,34 @@
package main
import ("net/http"; "fmt"; "strings")
func hello(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(res, "Hello canonical world")
}
func wrapCanonicalHost(f http.HandlerFunc, canonicalHost string) http.HandlerFunc {
return func(res http.ResponseWriter, req *http.Request) {
hostPort := strings.Split(req.Host, ":")
host := hostPort[0]
if host != canonicalHost {
fmt.Println("redirecting from", host, "to", canonicalHost)
hostPort[0] = canonicalHost
url := "http://" + strings.Join(hostPort, ":") + req.URL.String()
http.Redirect(res, req, url, 301)
}
f(res, req)
}
}
func main() {
handler := wrapCanonicalHost(hello, "localhost")
http.HandleFunc("/", handler)
http.ListenAndServe(":5000", nil)
}
// == running
// $ go run xx-http-server-canonical-host.go
//
// $ curl -i -L http://127.0.0.1:5000/go
// $ curl -i -L http://127.0.0.1:5000/go