golang http 连接超时和传输超时的例子
golang 测试代码
package main import ( "net/http" "net/url" "fmt" "io/ioutil" "time" "net" "crypto/tls" ) func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) { return func(netw, addr string) (net.Conn, error) { conn, err := net.DialTimeout(netw, addr, cTimeout) if err != nil { return nil, err } conn.SetDeadline(time.Now().Add(rwTimeout)) return conn, nil } } func main() { connectTimeout := 5 * time.Second readWriteTimeout := 100 * time.Millisecond c := http.Client{ Transport: &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, Dial: TimeoutDialer(connectTimeout, readWriteTimeout), }, } uri := "https://www.youtobe.com" req, err := http.NewRequest(http.MethodPost, uri, nil) if err != nil { fmt.Println("req error:" + err.Error()) return } req.Header = http.Header{} req.Header["Connection"] = []string{"Close"} req.Header["User-Agent"] = []string{"wpt-http-client/1.1"} data := make(url.Values) data["name"] = []string{"baixs"} data["hobby"] = []string{"runing"} resp, err := c.Do(req) if err != nil { fmt.Println("do error,err:" + err.Error()) return } respBody, err := ioutil.ReadAll(resp.Body) fmt.Println(string(respBody)) }
测试结果
连接超时(包括握手)
传输超时(也就是读写,从accept开始计算 )
相关推荐
Lzs 2020-10-23
Justhavefun 2020-10-22
周游列国之仕子 2020-09-15
风雨断肠人 2020-09-04
GoatSucker 2020-11-23
CoderToy 2020-11-16
蛰脚踝的天蝎 2020-11-10
ZGCdemo 2020-11-09
86193952 2020-10-27
hjr 2020-10-21
HELLOBOY 2020-10-21
qidiantianxia 2020-10-21
cmsmdn 2020-10-21
myspace 2020-10-21
笑面依旧 2020-10-21
专注前端开发 2020-10-21
技术之博大精深 2020-10-16
zhushenghan 2020-11-09