alienth
alienth

Reputation: 349

Is there a standard way to encode a URI component containing both forward-slashes and whitespace in Go?

I'm interacting with an API which takes URI components that may contain both forward-slashes and spaces. I need to percent-encode this URI component so that both the forward-slashes and spaces are properly encoded. Example Go code can be found here.

I turned to net/url to tackle this, but turns out it doesn't do what I want, apparently.

Since I'm very likely to muck this up (escaping is non-trivial), I'd prefer I relied upon some standard library out there to do this for me. Does such a standard method exist in a well-tested Go library?

Side note: The behaviour I'm seeking is identical to JS's encodeURIcomponent.

Upvotes: 4

Views: 1856

Answers (1)

Josh Lubawy
Josh Lubawy

Reputation: 396

Apparently a version of your issue made it in go1.8 as url.PathEscape.

In go1.8 the code you're looking for would be as simple as:

package main

import (
    "fmt"
    "net/url"
)

const expected = "/object/test%2Fbar%20baz"

func main() {
    uri := "/object/"
    name := "test/bar baz"

    fmt.Printf("%-25s %s\n", "Expected:", expected)
    fmt.Printf("%-25s %s\n", "Actual  :", uri+url.PathEscape(name))
}

Good question.

Upvotes: 1

Related Questions