Check if a URL is reachable using Golang
Asked Answered
A

4

19

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.

Astrosphere answered 14/2, 2017 at 13:4 Comment(3)
"but when the URL is down, it [http.Get] generates a panic call". No it doesn't.Carminecarmita
You want to know if something is listening for TCP connections on a given port,or you want to know if a web server is running there, and will serve a given URL?Borne
@Carminecarmita You're right, sorry about that. This is the first time I'm having a go at Go. I removed that detail from my question.Astrosphere
C
30

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)
}
Coonskin answered 14/2, 2017 at 13:13 Comment(1)
If you're only checking that the host is reachable, don't forget to conn.Close() or defer conn.Close().Auroraauroral
W
14

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.

Wendall answered 14/2, 2017 at 17:17 Comment(0)
I
7

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

Idocrase answered 18/4, 2021 at 21:44 Comment(0)
J
2

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
}
Jaunitajaunt answered 22/10, 2019 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.