mirror of
https://github.com/go-shiori/shiori.git
synced 2025-01-15 12:27:43 +08:00
fix: url modification when query param is empty (#411)
This commit fixes URL malformation when trying to remove the utm social query parameters from an URL, which upon finishing and reconstructing would attach the equal symbol even if the original URL didn't have it. This is a known Go "bug" [1] that isn't going to be "fixed". I quote that because server side should behave the same for `?a=&b=1` and `?a&b=1` for the `a` parameter, but sometimes that's not the case. [1]: https://github.com/golang/go/issues/20820 Fixes #409
This commit is contained in:
parent
81d52a2e24
commit
0fe24d2598
1 changed files with 31 additions and 1 deletions
|
@ -3,9 +3,39 @@ package core
|
|||
import (
|
||||
"fmt"
|
||||
nurl "net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// queryEncodeWithoutEmptyValues is a copy of `values.Encode` but checking if the queryparam
|
||||
// value is empty to prevent sending the = symbol empty which breaks in some servers.
|
||||
func queryEncodeWithoutEmptyValues(v nurl.Values) string {
|
||||
if v == nil {
|
||||
return ""
|
||||
}
|
||||
var buf strings.Builder
|
||||
keys := make([]string, 0, len(v))
|
||||
for k := range v {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
vs := v[k]
|
||||
keyEscaped := nurl.QueryEscape(k)
|
||||
for _, v := range vs {
|
||||
if buf.Len() > 0 {
|
||||
buf.WriteByte('&')
|
||||
}
|
||||
buf.WriteString(keyEscaped)
|
||||
if v != "" {
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(nurl.QueryEscape(v))
|
||||
}
|
||||
}
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// RemoveUTMParams removes the UTM parameters from URL.
|
||||
func RemoveUTMParams(url string) (string, error) {
|
||||
// Parse string URL
|
||||
|
@ -23,6 +53,6 @@ func RemoveUTMParams(url string) (string, error) {
|
|||
}
|
||||
|
||||
tmp.Fragment = ""
|
||||
tmp.RawQuery = queries.Encode()
|
||||
tmp.RawQuery = queryEncodeWithoutEmptyValues(queries)
|
||||
return tmp.String(), nil
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue