dongshi6969 2014-10-25 21:40
浏览 7
已采纳

转到测试网站状态(ping)

Is there any other better way to ping websites and check if the website is available or not?

I just need to get the status code not get(download) all websites...

func Ping(domain string) int {
    timeout := time.Duration(2 * time.Second)
    dialTimeout := func(network, addr string) (net.Conn, error) {
        return net.DialTimeout(network, addr, timeout)
    }
    transport := http.Transport{
        Dial: dialTimeout,
    }
    client := http.Client{
        Transport: &transport,
    }
    url := "http://" + domain
    req, _ := http.NewRequest("GET", url, nil)
    resp, _ := client.Do(req)
    return resp.StatusCode
}

This function is too slow and when I run with goroutines, it goes over the limits and gives me the errors...

Thanks!

  • 写回答

1条回答 默认 最新

  • dongsui4658 2014-10-26 00:32
    关注
    • Use a single transport. Because the transport maintains a pool of connections, you should not create and ignore transports willy nilly.
    • Close the response body as described at the beginning of the net/http doc.
    • Use HEAD if you are only interested in the status.
    • Check errors.

    Code:

    var client = http.Client{
      Transport: &http.Transport{
        Dial: net.Dialer{Timeout: 2 * time.Second}.Dial,
      },
    }
    
    func Ping(domain string) (int, error) {
        url := "http://" + domain
        req, err := http.NewRequest("HEAD", url, nil)
        if err != nil {
           return 0, err
        }
        resp, err := client.Do(req)
        if err != nil {
           return 0, err
        }
        resp.Body.Close()
        return resp.StatusCode, nil
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码