Skip to content

Instantly share code, notes, and snippets.

@hnaohiro
Created January 24, 2013 20:57
Show Gist options
  • Save hnaohiro/4627658 to your computer and use it in GitHub Desktop.
Save hnaohiro/4627658 to your computer and use it in GitHub Desktop.
Golang URL Encode
func urlencode(s string) (result string){
for _, c := range(s) {
if c <= 0x7f { // single byte
result += fmt.Sprintf("%%%X", c)
} else if c > 0x1fffff {// quaternary byte
result += fmt.Sprintf("%%%X%%%X%%%X%%%X",
0xf0 + ((c & 0x1c0000) >> 18),
0x80 + ((c & 0x3f000) >> 12),
0x80 + ((c & 0xfc0) >> 6),
0x80 + (c & 0x3f),
)
} else if c > 0x7ff { // triple byte
result += fmt.Sprintf("%%%X%%%X%%%X",
0xe0 + ((c & 0xf000) >> 12),
0x80 + ((c & 0xfc0) >> 6),
0x80 + (c & 0x3f),
)
} else { // double byte
result += fmt.Sprintf("%%%X%%%X",
0xc0 + ((c & 0x7c0) >> 6),
0x80 + (c & 0x3f),
)
}
}
return result
}
@UndeadBaneGitHub
Copy link

UndeadBaneGitHub commented Oct 31, 2022

To add a cherry on top: QueryEscape incorrectly escapes already escaped strings over and over again, which is straight up ridiculous.

It's 2022 and it still does this.

https://go.dev/play/p/Lwu-ixIwMB3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment