Go HTTP 小结 发表于 2016-10-10 | 分类于 Go 可能是史上最全的golang实现HTTP客户端的总结了,再附上一个变态的的服务器代码 以下脚本总共创建了6个函数:用三种方法实现了http请求,和一个服务器监听. 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113package mainimport ( "fmt" "strings" "net/http" "net/url" "io/ioutil")func main(){ uri := "http://localhost:8089/?hello=world" mime := "application/x-www-form-urlencoded" params := url.Values{"name": {"xiie"}, "from": {"wuhan"}} get_content := httpGet(uri) client_get := clientGet(uri) post_content := httpPost(uri,mime,params.Encode()) client_post := clientPost(uri,mime,params.Encode()) form_content := postForm(uri,params) fmt.Println(get_content) fmt.Println(client_get) fmt.Println(post_content) fmt.Println(client_post) fmt.Println(form_content) // http_server()}// net/http包 GET请求func httpGet(uri string) string{ response,_ := http.Get(uri) defer response.Body.Close() body,_ := ioutil.ReadAll(response.Body) return string(body)}// net/http包 POST请求func httpPost(uri string,mime string,params string) string{ resp, err := http.Post(uri,mime,strings.NewReader(params)) if err != nil { fmt.Println(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } return string(body)}// net/http client GET请求func clientGet(uri string) string{ client := &http.Client{} reqest, _ := http.NewRequest("GET", uri, nil) reqest.Header.Set("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8") reqest.Header.Set("Accept-Charset","GBK,utf-8;q=0.7,*;q=0.3") reqest.Header.Set("Accept-Encoding","gzip,deflate,sdch") reqest.Header.Set("Accept-Language","zh-CN,zh;q=0.8") reqest.Header.Set("Cache-Control","max-age=0") reqest.Header.Set("Connection","keep-alive") response,_ := client.Do(reqest) body, _ := ioutil.ReadAll(response.Body) defer response.Body.Close() //一定要关闭resp.Body return string(body)}// net/http client POST请求func clientPost(uri string, mime string, params string) string{ client := &http.Client{} req, _ := http.NewRequest("POST", uri, strings.NewReader(params)) req.Header.Set("Content-Type", mime) resp, _ := client.Do(req) defer resp.Body.Close() data, _ := ioutil.ReadAll(resp.Body) return string(data)}// net/http PostForm POST请求func postForm(uri string,params url.Values) string{ resp, err := http.PostForm("http://www.01happy.com/demo/accept.php",params) if err != nil { // handle error } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { // handle error } return string(body)}// HTTP server// golang服务端的效率没有node.js高,几乎是它的一半.func http_server(){ http.HandleFunc("/hello", func(w http.ResponseWriter, req *http.Request){//匿名函数 w.Write([]byte("Hello,philo xiie")) }) http.ListenAndServe(":8088", nil)}