Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate URL with standard package in GO

Tags:

validation

go

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.

like image 803
theduke Avatar asked Jul 17 '15 16:07

theduke


2 Answers

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") 
like image 76
Not_a_Golfer Avatar answered Sep 17 '22 13:09

Not_a_Golfer


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

like image 27
jchavannes Avatar answered Sep 17 '22 13:09

jchavannes