moar roouting

This commit is contained in:
Mark McGranaghan 2012-09-20 13:16:47 -07:00
parent 576216d105
commit 0939b1ebcd
5 changed files with 74 additions and 1 deletions

3
README
View File

@ -69,6 +69,8 @@ custom error pages
* 99 designes
* http://code.google.com/p/go-wiki/wiki/SliceTricks
* http://code.google.com/p/go-wiki/wiki/BoundingResourceUse
* https://groups.google.com/group/gorilla-web
* http://shadynasty.biz/blog/2012/08/07/painless-web-handlers-in-go/
= topics
* websockets
@ -78,6 +80,7 @@ custom error pages
* noblocking send and non-blocking receive
* dropping sends if buffer full
* web app
* default response
* accessing header values and query params
* accessing post body
* simultaneous assignment

View File

@ -12,6 +12,12 @@ func main() {
http.ListenAndServe(":5000", p)
}
// == todo
// consider gorilla-web
// defaults
// fallthroughs
// not found
// == running
// $ go get github.com/bmizerany/pat
// $ go run xx-http-server-routing.go

View File

@ -0,0 +1,29 @@
package main
import "net/http"
func hello(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
res.Write([]byte("Hello From HTTP\n"))
}
func main() {
helloHandler := http.HandlerFunc(hello)
staticHandler := http.StripPrefix("/static/", http.FileServer(http.Dir("./")))
http.Handle("/hello", helloHandler)
http.Handle("/static/", staticHandler)
http.ListenAndServe(":5000", nil)
}
// == running
// $ cd src
// $ go run xx-http-server-static-dynamic.go
//
// $ curl http://127.0.0.1:5000/hello
// $ curl http://127.0.0.1:5000/static
// $ curl http://127.0.0.1:5000/static/01-hello.go
// == todo
// try to get dynamic at root
// try to get static at root
// favicon

View File

@ -0,0 +1,36 @@
package main
import ("net/http"; "fmt"; "code.google.com/p/gorilla/mux")
func hello(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(res, "Hello")
}
func static(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
fmt.Fprintln(res, "Static")
}
func notFound(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/plain")
res.WriteHeader(404)
fmt.Fprintln(res, "Not found: /" + mux.Vars(req)["path"])
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/", hello)
r.HandleFunc("/favicon.ico", static)
r.HandleFunc("/{path:.*}", notFound)
http.ListenAndServe(":5000", r)
}
// == running
// $ go get code.google.com/p/gorilla/mux
// $ go run xx-http-server-static-select.go
//
// $ curl -i http://127.0.0.1:5000/
// $ curl -i http://127.0.0.1:5000/favicon.ico
// $ curl -i http://127.0.0.1:5000/wat
// $ curl -i http://127.0.0.1:5000/wat/wat

View File

@ -16,7 +16,6 @@ func main() {
// $ curl http://127.0.0.1:5000/missing
// == todo
// serving only a subpath as statically
// index pages
// disable listing
// custom 404 handling