Golang Code

How to check if a string is a URL

· 111 words · 1 minute read #check #function #http #location #parse #string #uri #url #valid

Here’s a little snippet to determine if a string is a 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.

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 url or not.
func isValidUrl(toTest string) bool {
    _, err := url.ParseRequestURI(toTest)
    if err != nil {
        return false
    } else {
        return true
    }
}
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.

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!