//get请求
func HttpGetT(addr string, timeout int) (ret string, err error) {
if timeout < 0 {
timeout = 5
}
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, time.Second*time.Duration(timeout)) //设置建立连接超时
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(time.Second * time.Duration(timeout))) //设置发送接受数据超时
return conn, nil
},
},
}
res, err := client.Get(addr)
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
ret = string(body)
return
}
//post请求
func HttpPostT(addr string, data url.Values, timeout int) (ret string, err error) {
if timeout < 0 {
timeout = 5
}
client := &http.Client{
Transport: &http.Transport{
Dial: func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, time.Second*time.Duration(timeout)) //设置建立连接超时
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(time.Second * time.Duration(timeout))) //设置发送接受数据超时
return conn, nil
},
},
}
res, err := client.PostForm(addr, data)
if err != nil {
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return
}
ret = string(body)
return
}
这个是把返回的纯数据剥离出来,以字符串的形式返回了;如果想返回(*http.Response, error),只要直接返回res, err := client.PostForm(addr, data)的 res 和err就可以了,加上 defer res.Body.Close()。把下面的代码去掉,然后改下函数返回参数类型。
#3
更多评论