检查一个URL是否可达,使用Golang。

huangapple go评论88阅读模式
英文:

Check if a URL is reachable using Golang

问题

我想创建一个简单的脚本,用于检查特定的主机名和端口是否正在运行。我只想得到一个布尔值的响应,以判断该URL是否可用,但我不确定是否有一种简单直接的方法来实现这个。

英文:

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.

答案1

得分: 26

如果你只想检查一个URL是否可访问,你可以使用net.DialTimeout。像这样:

timeout := 1 * time.Second
conn, err := net.DialTimeout("tcp","mysyte:myport", timeout)
if err != nil {
    log.Println("网站不可访问,错误信息: ", err)
}
英文:

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

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

答案2

得分: 14

如果你想检查一个 Web 服务器是否响应某个 URL,你可以使用 net/http 发起一个 HTTP GET 请求。
如果服务器没有任何响应,你将会得到一个超时错误。你也可以检查响应的状态。

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

你可以通过初始化一个 http.Client 来更改默认的超时时间。

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

额外内容
Go 通常不依赖异常,内置的库通常不会引发 panic,而是将错误作为第二个返回值返回。
参见 为什么 Go 没有异常?
如果你调用一个本地函数时发生 panic,可以假设发生了非常严重的错误。

英文:

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.

答案3

得分: 6

你可以发送一个 HEAD 请求:

package main
import "net/http"

func head(s string) bool {
   r, e := http.Head(s)
   return e == nil && r.StatusCode == 200
}

func main() {
   b := head("https://stackoverflow.com")
   println(b)
}

https://golang.org/pkg/net/http#Head

英文:

You can make a HEAD request:

package main
import "net/http"

func head(s string) bool {
   r, e := http.Head(s)
   return e == nil && r.StatusCode == 200
}

func main() {
   b := head("https://stackoverflow.com")
   println(b)
}

https://golang.org/pkg/net/http#Head

答案4

得分: 2

如果你不介意端口的话,可以使用http.Get(web)

package main

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

func main() {
	web := os.Args[1]
	fmt.Println(webIsReachable(web))
}

func webIsReachable(web string) bool {
	response, errors := http.Get(web)

	if errors != nil {
		_, netErrors := http.Get("https://www.google.com")

		if netErrors != nil {
			fmt.Fprintf(os.Stderr, "无网络连接\n")
			os.Exit(1)
		}

		return false
	}

	if response.StatusCode == 200 {
		return true
	}

	return false
}
英文:

If you don't mind the port, use http.Get(web):

package main

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

func main() {
	web := os.Args[1]
	fmt.Println(webIsReachable(web))
}

func webIsReachable(web string) bool {
	response, errors := http.Get(web)

	if errors != nil {
		_, netErrors := http.Get("https://www.google.com")

		if netErrors != nil {
			fmt.Fprintf(os.Stderr, "no internet\n")
			os.Exit(1)
		}

		return false
	}

	if response.StatusCode == 200 {
		return true
	}

	return false
}

huangapple
  • 本文由 发表于 2017年2月14日 21:04:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/42226947.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定