How to Check if a String is a URL

· 123 words · 1 minute read

Here’s a little snippet to determine if a string is well structured and considered valid url. This can be useful for pre-empting if a http call will work - or preventing failures from even occurring. In this snippet we’re using a function to tidy this logic and make it reusable and we are essentially parsing the url and checking for any errors.

package main

import (
    "fmt"
    "net/url"
)

func main() {
    // = true
    fmt.Println(isValidUrl("http://www.golangcode.com"))

    // = false
    fmt.Println(isValidUrl("golangcode.com"))

    // = false
    fmt.Println(isValidUrl(""))
}

// isValidUrl tests a string to determine if it is a well-structured url or not.
func isValidUrl(toTest string) bool {
    _, err := url.ParseRequestURI(toTest)
    if err != nil {
        return false
    } else {
        return true
    }
}

check if a url is valid

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!