Last active
June 24, 2021 09:17
-
-
Save arxdsilva/287d2f553bf31611f92f3eb5e19b45ca to your computer and use it in GitHub Desktop.
Golang - How to validate URL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
@scottgreenup
Your solution passes for if "://" part is missing after scheme I believe?
Thanks
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
@sivalingams https://play.golang.org/p/hvn8wKzgur7