简单:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
)
func main() {
res, err := http.Get("https://www.haiyun.me/")
if err != nil {
return
}
//执行close之前一定要判断错误,如没有body会崩溃
defer res.Body.Close()
//重用连接一定要执行上和下两步
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
fmt.Println(res.Status)
for k, v := range res.Header {
fmt.Println(k, strings.Join(v, ""))
}
}
自定义client,连接读写超时及自定义head:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
)
var timeout = time.Duration(20 * time.Second)
func dialTimeout(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
func main() {
tr := &http.Transport{
//使用带超时的连接函数
Dial: dialTimeout,
//建立连接后读超时
ResponseHeaderTimeout: time.Second * 2,
//直接通过ip访问时设置sni
TLSClientConfig: &tls.Config{
ServerName: "www.haiyun.me",
},
}
client := &http.Client{
Transport: tr,
//总超时,包含连接读写
Timeout: timeout,
}
req, _ := http.NewRequest("GET", "https://www.haiyun.me", nil)
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Host", "www.haiyun.me")
res, err := client.Do(req)
if err != nil {
return
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
for k, v := range res.Header {
fmt.Println(k, strings.Join(v, ""))
}
}
使用代理及指定出口IP:
//使用HTTP PROXY
proxyUrl, err := url.Parse("http://host:port")
tr := &http.Transport{
Proxy: http.ProxyURL(proxyUrl),
}
//指定出口IP
ief, err := net.InterfaceByName("eth0")
addrs, err := ief.Addrs()
addr := &net.TCPAddr{
IP: addrs[0].(*net.IPNet).IP,
}
dia := net.Dialer{LocalAddr: addr}
tr := &http.Transport{
Dial: dia.Dial,
}
使用socks5代理:https://github.com/hailiang/socks
http://golang.org/pkg/net/http/#Client
http://golang.org/pkg/net/http/#Transport
http://golang.org/pkg/net/#Dialer