How to Check if a String is a URL

· 211 words · 1 minute read

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

ParseRequestURI() is our primary basic check, but it will allow strings like ‘Test: Test’ to pass (which we don’t want). We therefore combine it with a url parser to check that both a scheme (like http) and a host exist.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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
	}

	u, err := url.Parse(toTest)
	if err != nil || u.Scheme == "" || u.Host == "" {
		return false
	}

	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!