Is there any function in a standard package in GO that allows to validate a URL?
I have not found anything on my initial search, and I would prefer not to resort to regex checking.
Yep, url.ParseRequestURI
returns an error if the URL is not valid, not an absolute url, etc etc. url.Parse
returns valid on almost anything...
import "net/url" ... u, err := url.ParseRequestURI("http://google.com/") if err != nil { panic(err) }
The above example will not fail, but these will:
u, err := url.ParseRequestURI("http//google.com") u, err := url.ParseRequestURI("google.com") u, err := url.ParseRequestURI("/foo/bar")
The accepted answer allows empty http://
and relative urls like /foo/bar
. If you want a stricter check, this will reject those:
import "net/url"
func IsUrl(str string) bool {
u, err := url.Parse(str)
return err == nil && u.Scheme != "" && u.Host != ""
}
Example: https://play.golang.org/p/JngFarWPF2-
Which came from this answer: https://stackoverflow.com/a/25747925/744298
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With