handler 參數(w http.ResponseWriter, r *http.Request)html
go參數傳遞爲值傳遞,request長用來獲取參數等,因此直接傳遞指針比較好,而 ResponseWriter 是個接口,只要實現接口就行 無所謂傳不傳指針的問題。golang
package main import ( "net/http" "log" "io" ) func main() { http.Handle("/", sayHello) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } } func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello world, version 1") } //訪問 http://localhost:8080/
ServeMux 實際上是路由表,主要使用map結構,其實例必須實現 ServeHTTP() 方法服務器
mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}
指針
package main import ( "net/http" "io" "log" ) func main() { mux := http.NewServeMux() //路由表結構 mux.Handle("/", &MyHandler{}) //這裏註冊的是處理的指針,默認根路徑"/" mux.HandleFunc("/hello", sayHello) //註冊/hello err := http.ListenAndServe(":8080", mux) // 將mux 放入 if err != nil { log.Fatal(err) } } type MyHandler struct { } func (_ * MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "URL: " + r.URL.String() ) } func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello world, version 2") } //訪問 http://localhost:8080/ //訪問 http://localhost:8080/hello
本身實現Server 最重要的是須要本身在 ServeHTTP() 中實現路由轉發code
package main import ( "net/http" "io" "log" "time" ) var mux map[string]func(w http.ResponseWriter, r *http.Request) func main() { server := http.Server{ Addr : ":8080", //設置地址 Handler : &MyHandler{}, //設置處理handler ReadTimeout : 5 * time.Second, //設置超時時間 5S } //由於沒有提供方法,因此須要本身實現路由,而後在ServeHTTP中進行路由轉發 mux = make(map[string]func(w http.ResponseWriter, r *http.Request)) mux["/hello"] = sayHello mux["/bye"] = sayBye err := server.ListenAndServe() // 使用本身實例化的server if err != nil { log.Fatal(err) } } type MyHandler struct { } func (_ *MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { //由於這裏沒有方法,因此須要進行路由轉發 if h, ok := mux[r.URL.String()]; ok { h(w, r) //若是存在就轉發 return } io.WriteString(w, "URL: " + r.URL.String()) } func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello world, version 3") } func sayBye(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "bye bye, version 3") } //訪問 http://localhost:8080/ //訪問 http://localhost:8080/hello //訪問 http://localhost:8080/bye
靜態文件就須要使用到http.FileServerserver
package main import ( "net/http" "io" "log" "os" ) func main() { mux := http.NewServeMux() mux.Handle("/", &MyHandler{}) mux.HandleFunc("/hello", sayHello) wd, err := os.Getwd()// 獲取當前路徑 if err != nil { log.Fatal(err) } //http.Dir(wd) //獲取相對路徑 //http.FileServer 靜態處理 mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(wd)))) //設置靜態文件路徑 err = http.ListenAndServe(":8080", mux) if err != nil { log.Fatal(err) } } type MyHandler struct { } func (_ * MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "URL: " + r.URL.String() ) } func sayHello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello world, version 4") } // http://localhost:8080/static/