-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp请求
92 lines (86 loc) · 1.81 KB
/
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
1.获取http状态码
package main
//获取http状态码
import (
"fmt"
"net/http"
"net/url"
)
func GET() {
u, _ := url.Parse("http://www.baidu.com/")
q := u.Query()
u.RawQuery = q.Encode()
res, err := http.Get(u.String())
if err != nil {
fmt.Println("0")
return
}
resCode := res.StatusCode
res.Body.Close()
if err != nil {
fmt.Println("0")
return
}
fmt.Printf("%d\r\n", resCode)
}
func main() {
GET()
}
2.获取网页源码
package main
import (
"net/http"
"fmt"
"io/ioutil"
)
func main() {
get()
}
func get(){
resp,err := http.Get("http://www.baidu.com")
if err!=nil {
fmt.Println("error=",err,";")
}
defer resp.Body.Close()
b,err:=ioutil.ReadAll(resp.Body)
fmt.Print(string(b))
}
3. 写一个简单的网页应用
package main
import (
"io"
"net/http"
)
const form = `
<html><body>
<form action="#" method="post" name="bar">
<input type="text" name="in" />
<input type="submit" value="submit"/>
</form>
</body></html>
`
/* handle a simple get request */
func SimpleServer(w http.ResponseWriter, request *http.Request) {
io.WriteString(w, "<h1>hello, world</h1>")
}
func FormServer(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Content-Type", "text/html")
switch request.Method {
case "GET":
/* display the form to the user */
io.WriteString(w, form)
case "POST":
/* handle the form data, note that ParseForm must
be called before we can extract form data */
//request.ParseForm();
//io.WriteString(w, request.Form["in"][0])
io.WriteString(w, request.FormValue("in"))
}
}
func main() {
http.HandleFunc("/test1", SimpleServer)
http.HandleFunc("/test2", FormServer)
if err := http.ListenAndServe(":8088", nil); err != nil {
panic(err)
}
}