URL is a valid one. URLs are often passed from third parties or user input, so they need to be checked before used. This function allows you to do just that, it will return true if the string is a valid URL. Feel free to copy and paste it and go from there.

e.g. valid “https://gophercoding.com/"

e.g. invalid “test string”

">

Check If a URL is Valid (original) (raw)

Written byEdd Turtle on gophercoding.com
on 4th of November 2024

This is just a quick post showing how we can check if a URL is a valid one. URLs are often passed from third parties or user input, so they need to be checked before used. This function allows you to do just that, it will return true if the string is a valid URL. Feel free to copy and paste it and go from there.

e.g. valid “https://gophercoding.com/"

e.g. invalid “test string”

| 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 33 | package main import ( "fmt" "net/url" ) func main() { myURL := "https://gophercoding.com/" if isValidURL(myURL) { fmt.Println(myURL, "is valid") } else { fmt.Println(myURL, "is not valid") } } // isValidURL checks if a given url matches a correct syntax of a webpage or URI // by pre-parsing strings to make sure they are valid before attempting requests. func isValidURL(toTest string) bool { u, err := url.Parse(toTest) if err != nil || u.Scheme == "" | | u.Host == "" { return false } _, err = url.ParseRequestURI(toTest) if err != nil { return false } return true } | | ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |

Example In Action

unix time

Author Edd Turtle

Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.

Tweet me!☕ Buy me a Coffee