diff --git a/README b/README index 07a9e5f..6c7f092 100644 --- a/README +++ b/README @@ -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 diff --git a/src/33-methods.go b/src/33-methods.go index 128fad2..ff02f17 100644 --- a/src/33-methods.go +++ b/src/33-methods.go @@ -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 diff --git a/src/xx-http-server-canonical-host.go b/src/xx-http-server-canonical-host.go new file mode 100644 index 0000000..457ffce --- /dev/null +++ b/src/xx-http-server-canonical-host.go @@ -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