Client -> Requests -> [Multiplexer(router) -> handler -> Response -> Client
cookie
http.HandleFunc("/", indexHandler) http.ListenAndServe("127.0.0.1:8000", nil) 或 server := &Server{Addr: addr, Handler: handler} server.ListenAndServe()
import ( "fmt" "net/http" ) func Hello(w http.ResponseWriter, r *http.Request) { fmt.Println("Hello World.") fmt.Fprintf(w, "Hello World.\n") } func main() { http.HandleFunc("/", Hello) err := http.ListenAndServe("0.0.0.0:6000", nil) if err != nil { fmt.Println("http listen failed.") } }
package main import ( "fmt" "net/http" "log" "reflect" "bytes" ) func main() { resp, err := http.Get("http://www.baidu.com") if err != nil { log.Println(err) return } defer resp.Body.Close() //關閉連接 headers := resp.Header for k, v := range headers { fmt.Printf("k=%v, v=%v\n", k, v) //全部頭信息 } fmt.Printf("resp status %s,statusCode %d\n", resp.Status, resp.StatusCode) fmt.Printf("resp Proto %s\n", resp.Proto) fmt.Printf("resp content length %d\n", resp.ContentLength) fmt.Printf("resp transfer encoding %v\n", resp.TransferEncoding) fmt.Printf("resp Uncompressed %t\n", resp.Uncompressed) fmt.Println(reflect.TypeOf(resp.Body)) buf := bytes.NewBuffer(make([]byte, 0, 512)) length, _ := buf.ReadFrom(resp.Body) fmt.Println(len(buf.Bytes())) fmt.Println(length) fmt.Println(string(buf.Bytes())) }
package main import ( "net/http" "strings" "io/ioutil" "log" "fmt" ) func main() { client := &http.Client{} req, err := http.NewRequest("POST", "http://www.baidu.com", strings.NewReader("name=xxxx&passwd=xxxx")) if err != nil { fmt.Println(err) return } req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") //設置請求頭信息 resp, err := client.Do(req) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Println(err) return } var res string res = string(body[:]) fmt.Println(res) }
package main import ( "net/http" "strings" "fmt" "io/ioutil" ) func main() { resp, err := http.Post("http://www.baidu.com", "application/x-www-form-urlencoded", strings.NewReader("username=xxx&password=xxxx")) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }
package main import ( "net/http" "fmt" "io/ioutil" "net/url" ) func main() { postParam := url.Values{ "name": {"wd"}, "password": {"1234"}, } resp, err := http.PostForm("https://cn.bing.com/", postParam) if err != nil { fmt.Println(err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) }