Skip to content

Instantly share code, notes, and snippets.

@dolmen
Created June 12, 2020 17:12
Show Gist options
  • Save dolmen/1a5fefcaf1a759568309d0612c4e8734 to your computer and use it in GitHub Desktop.
Save dolmen/1a5fefcaf1a759568309d0612c4e8734 to your computer and use it in GitHub Desktop.
Fix malformed URL query
// Fix (some kinds of) malformed URLs
package main
import (
"fmt"
"log"
"net/url"
)
func main() {
s := "https://boulanger.scene7.com/is/image/Boulanger/bfr_overlay?layer=comp&$t1=&$product_id=Boulanger/6901443378982_h_f_l_0&$i3=playstore non installé&wid=170&hei=170&fmt=jpg&qlt=85,0&resMode=sharp2&op_usm=1.75,0.3,2,0"
u, err := url.Parse(s)
if err != nil {
log.Fatal(err)
}
if u.RawQuery != "" {
i := 0
var b []byte
for j := 0; j < len(u.RawQuery); j++ {
c := u.RawQuery[j]
switch {
case c >= 127 || c <= ' ':
fmt.Println(c)
if j > i {
if i == 0 {
b = make([]byte, 0, len(u.RawQuery)+2)
}
b = append(b, u.RawQuery[i:j]...)
i = j
}
if c == ' ' {
b = append(b, '+')
} else {
b = append(b, '%')
const upperhex = "0123456789ABCDEF"
b = append(b, upperhex[c>>4])
b = append(b, upperhex[c&15])
}
i++
default:
}
}
if i > 0 {
u.RawQuery = string(append(b, u.RawQuery[i:]...))
}
}
u.Opaque = ""
fmt.Println("Original:", s)
fmt.Println("Fix: ", u.String())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment