使用Golang检查网址是否可访问

使用Golang检查网址是否可访问

问题描述:

I want to create a simple script that checks if a certain hostname:port is running. I only want to get a bool response if that URL is live, but I'm not sure if there's a straightforward way of doing it.

我想创建一个简单的脚本来检查某个主机名:端口是否正在运行。 如果该URL是实时的,我只想得到一个 bool code>响应,但是我不确定是否有直接的方法。 p> div>

If you only want see if a URL is reachable you could use net.DialTimeout. Like this:

timeout := time.Duration(1 * time.Second)
conn, err := net.DialTimeout("tcp","mysyte:myport", timeout)
if err != nil {
    log.Println("Site unreachable, error: ", err)
}

If you want to check if a Web server answers on a certain URL, you can invoke an HTTP GET request using net/http. You will get a timeout if the server doesn't response at all. You might also check the response status.

resp, err := http.Get("http://google.com/")
if err != nil {
    print(err.Error())
} else {
    print(string(resp.StatusCode) + resp.Status)
}

You can change the default timeout by initializing a http.Client.

timeout := time.Duration(1 * time.Second)
client := http.Client{
    Timeout: timeout,
}
resp, err := client.Get("http://google.com")

Bonus: Go generally does not rely on exceptions and the built in libraries generally do not panic, but return an error as a second value. See Why does Go not have exceptions?. You can assume that something very bad happened if your call to a native function panics.