Encode / decode URLs

后端 未结 8 1509
攒了一身酷
攒了一身酷 2020-11-28 03:46

What\'s the recommended way of encoding and decoding entire URLs in Go? I am aware of the methods url.QueryEscape and url.QueryUnescape, but they d

8条回答
  •  独厮守ぢ
    2020-11-28 04:23

    From MDN on encodeURIComponent:

    encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, '-', '_', '.', '!', '~', '*', ''', '(', ')'

    From Go's implementation of url.QueryEscape (specifically, the shouldEscape private function), escapes all characters except the following: alphabetic, decimal digits, '-', '_', '.', '~'.

    Unlike Javascript, Go's QueryEscape() will escape '!', '*', ''', '(', ')'. Basically, Go's version is strictly RFC-3986 compliant. Javascript's is looser. Again from MDN:

    If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:

    function fixedEncodeURIComponent (str) {
      return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
    }
    

提交回复
热议问题