Petr Razumov
Petr Razumov

Reputation: 2142

How to add scheme and path to url.URL

I'm trying to update a parsed URL the following way:

u, _ := url.Parse(s)
if u.Scheme == "" {
    u.Scheme = "https"
}
if u.Path == "" {
    u.Path = "api"
}

But it turns out that if the initial string lacks the URL scheme (e.g. example.com) that string is parsed as URL.Path and not URL.Host. See this Go playground link.

How can I turn this example.com into this https://example.com/api?

Upvotes: 1

Views: 2967

Answers (2)

Verran
Verran

Reputation: 4062

The Parse function works off of RFC 3986 Section 3 which requires the authority (host and port) to be preceeded by //.

URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ]

hier-part = "//" authority path-abempty / path-absolute / path-rootless / path-empty

According to this spec the leading // is required and the Parse function enforces that. The string you pass to the Parse function can include a blank URL scheme, but it does have to include a // before the hostname and port for it to parse those parts correctly. How you want to enforce having that leading // is up to you.

Upvotes: 1

Eugene Lisitsky
Eugene Lisitsky

Reputation: 12845

You may add a check:

if !strings.HasPrefix(s, "http://") && !strings.HasPrefix(s, "https://") {
        s = "https://" + s
}

https://play.golang.org/p/dDK0nx-8x-

Upvotes: 2

Related Questions