Skip to content

Instantly share code, notes, and snippets.

@arxdsilva
Last active June 24, 2021 09:17
Show Gist options
  • Save arxdsilva/287d2f553bf31611f92f3eb5e19b45ca to your computer and use it in GitHub Desktop.
Save arxdsilva/287d2f553bf31611f92f3eb5e19b45ca to your computer and use it in GitHub Desktop.
Golang - How to validate URL
import (
"fmt"
"github.com/asaskevich/govalidator"
)
// You can use as well instead of *url.URL a string with your URL, in this case you might drop `u.String()`
// - transformation to string in method call.
func validateURL(u *url.URL) error {
valid := govalidator.IsRequestURL(u.String())
if valid == false {
return fmt.Errorf("%v is a invalid url", u.String())
}
return nil
}
@sivalingams
Copy link

import "net/url"
u, err := url.ParseRequestURI("https://google.com/")
if err != nil {
// Handle error
}

@scottgreenup
Copy link

@challarao
Copy link

@scottgreenup
Your solution passes for if "://" part is missing after scheme I believe?

Thanks

@kanazir
Copy link

kanazir commented Jun 24, 2021

import "net/url"
u, err := url.ParseRequestURI("https://google.com/")
if err != nil {
// Handle error
}

Try this:

for _, u := range []string{`http://`, `https://`, `http://goo`} {
	_, err := url.ParseRequestURI(u)
	if err != nil {
		fmt.Println(u+`:`, err)
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment