Reputation: 349
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.
url.QueryEscape()
is intended for query strings, and as such it turns whitespace into +
rather than %20
.url.Parse()
and url.ParseRequestUri()
will turn whitespace into %20
, but it will ignore /
, as it should.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
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