Reputation: 17981
Say I have this url
https://example.com:8080?private-token=foo&authenticity_token=bar
And I have a function to determine whether to mask a param.
How can I mask the url, but maintaining the order of params.
Currently I have
u, err := url.Parse(originalURL)
if err != nil {
panic(err)
}
m, _ := url.ParseQuery(u.RawQuery)
for key := range m {
if toMask(key) {
m.Set(key, "FILTERED")
}
}
u.RawQuery = m.Encode()
return u.String()
But this would return url with the params being switched around.
https://example.com:8080?authenticity_token=FILTERED&private-token=FILTERED
Upvotes: 0
Views: 1880
Reputation: 66
First, the order of the params should not be of any importance.
But I can see some situation where this rule does not apply (eg when you hash an URL). In this case, you should normalize the URL before using it.
Finally to respond to your question, you cannot keep the order if using Query, as Values is a map, and map don't bother with ordering. You should thus work on the query using u.RawQuery
.
u, err := url.Parse(originalURL)
if err != nil {
panic(err)
}
newQuery := ""
for i, queryPart := range strings.Split(u.RawQuery, ";") {
// you now have a slice of string ["private-token=foo", "authenticity_token=bar"]
splitParam := strings.Split(queryPart, "=")
if toMask(splitParam[0]) {
splitParam[1] = "FILTERED"
}
if i != 0 {
newQuery = newQuery + ";"
}
newQuery = splitParam[0] + "=" + splitParam[1]
}
u.RawQuery = newQuery
return u.String()
This code is just example. You have to better check for special cases or errors. You can also use regexp if you want to.
Upvotes: 2