Go HTTP 小结

可能是史上最全的golang实现HTTP客户端的总结了,再附上一个变态的的服务器代码

以下脚本总共创建了6个函数:用三种方法实现了http请求,和一个服务器监听.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"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)
}