golang http 连接超时和传输超时的例子
程序员文章站
2022-08-30 12:41:48
golang 测试代码
package main
import (
"net/http"
"net/url"
"fmt"
"io/i...
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开始计算 )
以上这篇golang http 连接超时和传输超时的例子就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
下一篇: golang并发ping主机的方法