Fix wrong url check
url.Parse cannot check the validity of the url.
Here is a simple uinttest function.
func TestCheckURL(t *testing.T) {
//The value is true if the url is valid
urls := map[string]bool{
"http://elastic:elastic@localhost:9210": true,
"https://google.com": true,
"http://google.com/": true,
"http:/google.com": true,
"google.com": false,
"google/com": false,
"http//google.com": false,
"": false,
}
// http.Parse, all urls are right
for u, _ := range urls {
_, err := url.Parse(u)
assert.Nil(t, err)
}
// http.ParseRequestURI, some are right, and some not.
for u, b := range urls {
_, err := url.ParseRequestURI(u)
if b {
assert.Nil(t, err)
} else {
assert.NotNil(t, err, u)
}
}
}
=== RUN TestCheckURL
--- PASS: TestCheckURL (0.00s)
PASS
url.Parse cannot check the validity of the url.
That's a bold statement.
That's a bold statement.
But this is the truth. https://play.golang.org/p/_c5Ax7KJr--
@bestgopher Please check documentation in https://golang.org/pkg/net/url/#URL. In fact, "123456" from your example is parsed as a relative path without host or scheme. Technically, it is a valid URL. Of course, it might be unsuitable for some specific use cases. If you want to be sure that your path is a global path, you should check URL.Host after parsing. It is rather likely that you need to check URL.Scheme as well. For example, ftp://example.com is a valid URL, but it may be unsuitable for your use case.