How to check if a string is a URL

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
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *