入门

简单get请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package main

import (
"fmt"
"io/ioutil"
"net/http"
)

func main() {
resp, err := http.Get("https://www.liwenzhou.com/")
if err != nil {
fmt.Printf("get failed, err:%v\n", err)
return
}
// 使用完response后必须关闭回复的主体。
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("read from resp.Body failed, err:%v\n", err)
return
}
fmt.Print(string(body))
}

带参数get请求

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
import (
"fmt"
"io/ioutil"
"net/http"
"net/url"
)

func main() {
apiUrl := "http://127.0.0.1:9090/get"
// URL param
data := url.Values{}
data.Set("name", "小王子")
data.Set("age", "18")

u, err := url.ParseRequestURI(apiUrl)
if err != nil {
fmt.Printf("parse url requestUrl failed, err:%v\n", err)
}
u.RawQuery = data.Encode() // URL encode
fmt.Println(u.String()) // http://127.0.0.1:9090/get?age=18&name=%E5%B0%8F%E7%8E%8B%E5%AD%90

resp, err := http.Get(u.String())
if err != nil {
fmt.Printf("post failed, err:%v\n", err)
return
}
defer resp.Body.Close()

b, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("get resp failed, err:%v\n", err)
return
}
fmt.Println(string(b))
}

对应的Server端HandlerFunc

1
2
3
4
5
6
7
8
func getHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
data := r.URL.Query()
fmt.Println(data.Get("name"))
fmt.Println(data.Get("age"))
answer := `{"status": "ok"}`
w.Write([]byte(answer))
}

post请求

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
package main

import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)

func main() {
url := "http://127.0.0.1:9090/post"

// 表单form数据
// contentType := "application/x-www-form-urlencoded"
// data := "name=小王子&age=18"

// json数据
contentType := "application/json"
data := `{"name":"小王子","age":18}`

resp, err := http.Post(url, contentType, strings.NewReader(data))
if err != nil {
fmt.Printf("post failed, err:%v\n", err)
return
}
defer resp.Body.Close()

b, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Printf("get resp failed, err:%v\n", err)
return
}
fmt.Println(string(b))
}

对应的Server端HandlerFunc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func postHandler(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
// 1. 请求类型是application/x-www-form-urlencoded时解析form数据
r.ParseForm()
fmt.Println(r.PostForm) // 打印form数据
fmt.Println(r.PostForm.Get("name"), r.PostForm.Get("age"))

// 2. 请求类型是application/json时从r.Body读取数据
b, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Printf("read request.Body failed, err:%v\n", err)
return
}
fmt.Println(string(b))
answer := `{"status": "ok"}`
w.Write([]byte(answer))
}

postForm

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
package main

import (
"net/http"
"fmt"
"io/ioutil"
"net/url"
)

func main() {
postParam := url.Values{
"mobile": {"xxxxxx"},
"isRemberPwd": {"1"},
}

resp, err := http.PostForm("http://www.maimaiche.com/loginRegister/login.do", 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))
}

Go 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
package main

import (
"fmt"
"net/http"
"log"
"reflect"
"bytes"
)

func main() {
// 简单请求
resp, err := http.Get("http://www.baidu.com")
if err != nil {
// handle error
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)) // *http.gzipReader

// 读取response
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()))
}

设置头参数、cookie

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
package main

import (
"net/http"
"strings"
"fmt"
"io/ioutil"
"log"
"encoding/json"
)

func main() {
client := &http.Client{}

req, err := http.NewRequest("POST", "http://www.maimaiche.com/loginRegister/login.do",
strings.NewReader("mobile=xxxxxxxxx&isRemberPwd=1"))
if err != nil {
log.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
}

fmt.Println(resp.Header.Get("Content-Type")) //application/json;charset=UTF-8

type Result struct {
Msg string
Status string
Obj string
}

// 读取json到Result对象
result := &Result{}
json.Unmarshal(body, result) //解析json字符串

if result.Status == "1" {
fmt.Println(result.Msg)
} else {
fmt.Println("login error")
}
fmt.Println(result)
}