elastic icon indicating copy to clipboard operation
elastic copied to clipboard

Fix wrong url check

Open bestgopher opened this issue 4 years ago • 3 comments

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

bestgopher avatar May 27 '21 03:05 bestgopher

url.Parse cannot check the validity of the url.

That's a bold statement.

olivere avatar Jun 16 '21 09:06 olivere

That's a bold statement.

But this is the truth. https://play.golang.org/p/_c5Ax7KJr--

bestgopher avatar Jun 16 '21 10:06 bestgopher

@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.

mbalabin avatar Jun 16 '21 13:06 mbalabin