Skip to content

net/url: document what is a valid URL #18824

@dsnet

Description

@dsnet

This post on go-nuts is indicative that the url package is very frequently mis-used. Even when I was running go1.8 over Go code inside Google, incorrect usages of url.Parse were a frequent source of problems.

One very common mistake I see is something like the following:

u, err := url.Parse("192.168.0.1/path/to/endpoint")
fmt.Printf("%#v\n", u)

This is a valid URL, but it does not do what people expect it to do. When printed, it shows:

&url.URL{Host:"", Path:"192.168.0.1/path/to/endpoint"}

What the user was expecting was:

&url.URL{Host:"192.168.0.1", Path:"/path/to/endpoint"}

Notice that the IP address is part of the Path component and not the Host?

The current behavior is correct because the URL provided is not an absolute URL and therefore must be parsed as a relative URL. However, this behavior is not obvious.

In order to get around this issue, I have seen users do url.Parse("//192.168.0.1/path/to/endpoint") to achieve the desired behavior. While this properly parses "192.168.0.1" as the Host and "/path/to/endpoint" as the Path, it is not obvious to users that this is a valid URL. (this format is called the "network-path reference" from RFC 3986, section 4.2)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions