Skip to content

Instantly share code, notes, and snippets.

@czyang
Last active September 1, 2021 05:43
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save czyang/7ae30f4f625fee14cfc40c143e1b78bf to your computer and use it in GitHub Desktop.
Save czyang/7ae30f4f625fee14cfc40c143e1b78bf to your computer and use it in GitHub Desktop.
// #Warning! You Should Use this Code Carefully, and As Your Own Risk.
package main
import (
"fmt"
"net/url"
"strings"
)
/*
After hours searching, I can't find any method can get the result exact as the JS encodeURIComponent function.
In my situation I need to write a sign method which need encode the user input exact same as the JS encodeURIComponent.
This function does solved my problem.
*/
func main() {
params := url.Values{
"test_string": {"+!+'( )*-._~0-👿 👿9a-zA-Z 中文测试 test with ❤️ !@#$%^&&*()~<>?/.,;'[][]:{{}|{}|"},
}
urlEncode := params.Encode()
fmt.Println(urlEncode)
urlEncode = compatibleRFC3986Encode(urlEncode)
fmt.Println("RFC3986", urlEncode)
urlEncode = compatibleJSEncodeURIComponent(urlEncode)
fmt.Println("JS encodeURIComponent", urlEncode)
}
// Compatible with RFC 3986.
func compatibleRFC3986Encode(str string) string {
resultStr := str
resultStr = strings.Replace(resultStr, "+", "%20", -1)
return resultStr
}
// This func mimic JS encodeURIComponent, JS is wild and not very strict.
func compatibleJSEncodeURIComponent(str string) string {
resultStr := str
resultStr = strings.Replace(resultStr, "+", "%20", -1)
resultStr = strings.Replace(resultStr, "%21", "!", -1)
resultStr = strings.Replace(resultStr, "%27", "'", -1)
resultStr = strings.Replace(resultStr, "%28", "(", -1)
resultStr = strings.Replace(resultStr, "%29", ")", -1)
resultStr = strings.Replace(resultStr, "%2A", "*", -1)
return resultStr
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment