Go中的网络请求和数据转发

GET & 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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
var cfg = beego.AppConfig

type AddressController struct {
baseController
}

func (ac AddressController) Address() {
userId := ac.GetString("user_id")
var url = cfg.String("third::user_url") + "/user/address?user_id=" + userId
body, err := get(url)
if err != nil {
logs.Error("get Address error:", err)
return
}
ac.Data["json"] = string(body)
ac.ServeJSON()
}

func (ac AddressController) AddAddress() {
userId := ac.GetString("user_id")
var url = cfg.String("third::user_url") + "/user/add_address?user_id=" + userId

body, err := post(url, ac.Ctx.Input.RequestBody)
if err != nil {
logs.Error("post AddAddress error:", err)
return
}
ac.Data["json"] = string(body)
ac.ServeJSON()
}

func get(url string) ([]byte, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}

func post(url string, data []byte) ([]byte, error) {
body := bytes.NewBuffer(data)
resp, err := http.Post(url, "application/json;charset=utf-8", body)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}

参考资料