響應http的三種方法
阿新 • • 發佈:2017-12-29
object pla and lap code timeout request color urn
小編最近再看無聞的goweb視屏,總結視屏中三種go響應http的方法
1.直接用 http.HandleFunc() 函數
// object project main.go package main import ( "io" "log" "net/http" ) func main() { http.HandleFunc("/", sayhello) // 第一個參數代表訪問的路徑,第二個代表要執行的函數的名字 err := http.ListenAndServe(":8080", nil) //設置端口號,第二個暫時沒有,寫為nil,在接下來的方法中介紹View Codeif err != nil { log.Fatal(err) //如果err不為空,打印err } } //ResponseWriter為接口,Request為結構體 func sayhello(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "hello!this is version 1") }
2.介紹Handle方法
package main // dealFile project main.go import ( "io" "log" "net/http" "os" ) func main() {View Code//首先實現 NewServeMux()方法 max := http.NewServeMux() max.Handle("/", &myHandler{}) max.HandleFunc("/hello", sayhello) //靜態文件的實現 wd, err := os.Getwd() if err != nil { log.Fatal(err) } max.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir(wd))))//設置監聽的端口號 err = http.ListenAndServe(":8080", max) if err != nil { log.Fatal(err) } } type myHandler struct{} //實現ServeHTTP方法 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,this is version 2") }
3.Server
package main import ( "io" "log" "net/http" "time" ) var mux map[string]func(http.ResponseWriter, *http.Request) func main() { server := http.Server{ Addr: ":8080", //端口號 Handler: &myHandler{}, //實現的Handler ReadTimeout: 5 * time.Second, //響應等待時間 } mux = make(map[string]func(http.ResponseWriter, *http.Request)) mux["/hello"] = sayHello mux["/bye"] = sayBye err := server.ListenAndServe() if err != nil { log.Fatal(err) } } type myHandler struct{} func (*myHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { //判斷URL是否為空並輸出 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") } func sayBye(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "Bye Bye") }View Code
響應http的三種方法