httpgohttp-status-code-504bad-gateway

Check for Internet connection from application


I need to check if the user is connected to internet before I can proceed.

I am hitting the endpoint using HttpClient as follows:

client := &http.Client{}
req, _ := http.NewRequest("GET", url, nil)
req.SetBasicAuth(username, password)
res, err := client.Do(req)

if err != nil {
    fmt.Println(err)
    ui.Failed("Check your internet connection")
}

1) I need to show clear messages to the user if the user is not connected to the internet in this case, display "Please check your internet connection"

2) In case the server is not responding, and receives 504 bad gateway, display "504 Bad gateway"

Can someone help how to proceed and distinguish between these two scenarios and I would like to display only simple messages and not the entire error messages received from the server.


Solution

  • To check if you're connected to internet you can use this:

    func connected() (ok bool) {
        _, err := http.Get("http://clients3.google.com/generate_204")
        if err != nil {
            return false
        }
        return true
    }
    

    And to get the status code you can have it from res.StatusCode. The final result would be something like that:

    if !connected() {
        ui.Failed("Check your internet connection")
    }
    
    client := &http.Client{}
    req, _ := http.NewRequest("GET", url, nil)
    req.SetBasicAuth(username, password)
    res, _ := client.Do(req)
    
    if res.StatusCode == 504 {
        ui.Failed("504 Bad gateway")
    }
    

    (I'm ignoring other errors that obviusly you should check)