DEV Community

loading...

Check if user is connected to the internet in Go

obnoxiousnerd profile image Pranav Karawale ・2 min read

Here's a small function to check the internet connectivity.

The function

//Don't forget to import "net/http" first!

//IsOnline Check whether user is connected to the Internet or not.
//This method of checking can be unfunctional in some areas
//but there seems to be no downtime.
//
//See https://major.io/icanhazip-com-faq/ for more info about icanhazip
func IsOnline() bool {
    //Make a request to icanhazip.com
    //We need the error only, nothing else :)
    _, err := http.Get("https://icanhazip.com/")
    //err = nil means online
    if err == nil {
        return true
    }
    //if the "return statement" in the if didn't executed,
    //this one will execute surely
    return false
}
}
Enter fullscreen mode Exit fullscreen mode

Use cases

  • CLI Apps (useful if lots of APIs are waiting to be called)
  • Personal use
  • I leave this one for you

License to keep legal authorities happy

MIT License

Copyright (c) 2020 Pranav Karawale

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Enter fullscreen mode Exit fullscreen mode

Please don't forget to cite this site when using this function :)

Discussion

pic
Editor guide