go-head获取网站状态码并设置超时时间

package main

import (
	"fmt"
	"net"
	"net/http"
	"time"
)

var url = []string{
	"http://www.baidu.com",
	"http://google.com",
	"http://taobao.com",
}

func main() {
        //底层调用net的http.Client.Transport的方法
        // 自定义Transport 并设置timeout为2s,可以自定义
	for _, v := range url {
		c := http.Client{
			Transport: &http.Transport {
				Dial:func(network, addr string) (net.Conn, error){
					timeout := time.Second*2
					return net.DialTimeout(network, addr, timeout)
				},
			},
		}
		resp, err := c.Head(v)
		if err != nil {
			fmt.Printf("head %s failed, err:%v\n", v, err)
			continue
		}

		fmt.Printf("head succ, status:%v\n", resp.Status)
	}
}

 

 

 

 

posted @ 2022-05-26 16:51  随心朝阳  阅读(65)  评论(0编辑  收藏  举报