Encoder / décoder les URL

Quelle est la méthode recommandée pour encoder et décoder des URL complètes dans Go? Je connais les méthodes url.QueryEscape et url.QueryUnescape , mais elles ne semblent pas être exactement ce que je recherche. Plus précisément, je recherche des méthodes comme JavaScript encodeURIComponent et decodeURIComponent .

Merci.

Vous pouvez faire tout le codage URL souhaité avec le module net / url . Il ne divise pas les fonctions de codage individuelles pour les parties de l’URL, vous devez le laisser construire l’URL complète. Ayant eu un strabisme sur le code source, je pense que cela fait un travail très bien et conforme aux normes.

Voici un exemple ( lien de terrain de jeu )

 package main import ( "fmt" "net/url" ) func main() { var Url *url.URL Url, err := url.Parse("http://www.example.com") if err != nil { panic("boom") } Url.Path += "/some/path/or/other_with_funny_characters?_or_not/" parameters := url.Values{} parameters.Add("hello", "42") parameters.Add("hello", "54") parameters.Add("vegetable", "potato") Url.RawQuery = parameters.Encode() fmt.Printf("Encoded URL is %q\n", Url.Ssortingng()) } 

Quelles impressions

 Encoded URL is "http://www.example.com/some/path/or/other_with_funny_characters%3F_or_not/?vegetable=potato&hello=42&hello=54" 

De MDN sur encodeURIComponent :

encodeURIComponent échappe à tous les caractères sauf les suivants: alphabétique, chiffres décimaux, '-', '_', '.', '!', '~', '*', ''', '(', ')'

Depuis l’implémentation de url.QueryEscape de Go (spécifiquement, la fonction privée de shouldEscape ), elle échappe à tous les caractères sauf les suivants: alphabétique, chiffres décimaux, '-', '_', '.', '~' .

Contrairement à Javascript, QueryEscape () échappera à '!', '*', ''', '(', ')' . Fondamentalement, la version de Go est ssortingctement conforme à la norme RFC-3986. Javascript est plus souple. Encore de MDN:

Si l’on souhaite être plus rigoureux en adhérant à la RFC 3986 (qui réserve!, ‘, (,) Et *), même si ces caractères n’ont aucune utilisation de délimitation d’URI formalisée, les éléments suivants peuvent être utilisés en toute sécurité:

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

Que dis-tu de ça:

 template.URLQueryEscaper(path) 

À partir de Go 1.8, cette situation a changé. Nous avons maintenant access à PathEscape en plus de l’ancienne QueryEscape pour encoder les composants du chemin, ainsi que son homologue PathUnescape .

Pour imiter l’ encodeURIComponent() de Javascript, j’ai créé une fonction d’assistance de chaîne.

Exemple: Transforme "My Ssortingng" en "My%20Ssortingng"

https://github.com/mrap/ssortingngutil/blob/master/urlencode.go

 import "net/url" // UrlEncoded encodes a ssortingng like Javascript's encodeURIComponent() func UrlEncoded(str ssortingng) (ssortingng, error) { u, err := url.Parse(str) if err != nil { return "", err } return u.Ssortingng(), nil } 

Si quelqu’un veut obtenir le résultat exact par rapport à l’encodage JIC, il est sale mais fonctionne bien.

https://gist.github.com/czyang/7ae30f4f625fee14cfc40c143e1b78bf

 // #Warning! You Should Use this Code Carefully, and As Your Own Risk. package main import ( "fmt" "net/url" "ssortingngs" ) /* 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_ssortingng": {"+!+'( )*-._~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 } 

Voici une implémentation de escape et unescape (extraite de go source):

 package main import ( "fmt" "strconv" ) const ( encodePath encoding = 1 + iota encodeHost encodeUserPassword encodeQueryComponent encodeFragment ) type encoding int type EscapeError ssortingng func (e EscapeError) Error() ssortingng { return "invalid URL escape " + strconv.Quote(ssortingng(e)) } func ishex(c byte) bool { switch { case '0' <= c && c <= '9': return true case 'a' <= c && c <= 'f': return true case 'A' <= c && c <= 'F': return true } return false } func unhex(c byte) byte { switch { case '0' <= c && c <= '9': return c - '0' case 'a' <= c && c <= 'f': return c - 'a' + 10 case 'A' <= c && c <= 'F': return c - 'A' + 10 } return 0 } // Return true if the specified character should be escaped when // appearing in a URL string, according to RFC 3986. // // Please be informed that for now shouldEscape does not check all // reserved characters correctly. See golang.org/issue/5684. func shouldEscape(c byte, mode encoding) bool { // §2.3 Unreserved characters (alphanum) if 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || '0' <= c && c <= '9' { return false } if mode == encodeHost { // §3.2.2 Host allows // sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" // as part of reg-name. // We add : because we include :port as part of host. // We add [ ] because we include [ipv6]:port as part of host switch c { case '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=', ':', '[', ']': return false } } switch c { case '-', '_', '.', '~': // §2.3 Unreserved characters (mark) return false case '$', '&', '+', ',', '/', ':', ';', '=', '?', '@': // §2.2 Reserved characters (reserved) // Different sections of the URL allow a few of // the reserved characters to appear unescaped. switch mode { case encodePath: // §3.3 // The RFC allows : @ & = + $ but saves / ; , for assigning // meaning to individual path segments. This package // only manipulates the path as a whole, so we allow those // last two as well. That leaves only ? to escape. return c == '?' case encodeUserPassword: // §3.2.1 // The RFC allows ';', ':', '&', '=', '+', '$', and ',' in // userinfo, so we must escape only '@', '/', and '?'. // The parsing of userinfo treats ':' as special so we must escape // that too. return c == '@' || c == '/' || c == '?' || c == ':' case encodeQueryComponent: // §3.4 // The RFC reserves (so we must escape) everything. return true case encodeFragment: // §4.1 // The RFC text is silent but the grammar allows // everything, so escape nothing. return false } } // Everything else must be escaped. return true } func escape(s string, mode encoding) string { spaceCount, hexCount := 0, 0 for i := 0; i < len(s); i++ { c := s[i] if shouldEscape(c, mode) { if c == ' ' && mode == encodeQueryComponent { spaceCount++ } else { hexCount++ } } } if spaceCount == 0 && hexCount == 0 { return s } t := make([]byte, len(s)+2*hexCount) j := 0 for i := 0; i < len(s); i++ { switch c := s[i]; { case c == ' ' && mode == encodeQueryComponent: t[j] = '+' j++ case shouldEscape(c, mode): t[j] = '%' t[j+1] = "0123456789ABCDEF"[c>>4] t[j+2] = "0123456789ABCDEF"[c&15] j += 3 default: t[j] = s[i] j++ } } return ssortingng(t) } // unescape unescapes a ssortingng; the mode specifies // which section of the URL ssortingng is being unescaped. func unescape(s ssortingng, mode encoding) (ssortingng, error) { // Count %, check that they're well-formed. n := 0 hasPlus := false for i := 0; i < len(s); { switch s[i] { case '%': n++ if i+2 >= len(s) || !ishex(s[i+1]) || !ishex(s[i+2]) { s = s[i:] if len(s) > 3 { s = s[:3] } return "", EscapeError(s) } i += 3 case '+': hasPlus = mode == encodeQueryComponent i++ default: i++ } } if n == 0 && !hasPlus { return s, nil } t := make([]byte, len(s)-2*n) j := 0 for i := 0; i < len(s); { switch s[i] { case '%': t[j] = unhex(s[i+1])<<4 | unhex(s[i+2]) j++ i += 3 case '+': if mode == encodeQueryComponent { t[j] = ' ' } else { t[j] = '+' } j++ i++ default: t[j] = s[i] j++ i++ } } return string(t), nil } func EncodeUriComponent(rawString string) string{ return escape(rawString, encodeFragment) } func DecodeUriCompontent(encoded string) (string, error){ return unescape(encoded, encodeQueryComponent) } // https://golang.org/src/net/url/url.go // http://remove-line-numbers.ruurtjan.com/ func main() { // http://www.url-encode-decode.com/ origin := "äöüHel/lo world" encoded := EncodeUriComponent(origin) fmt.Println(encoded) s, _ := DecodeUriCompontent(encoded) fmt.Println(s) } 

 // ------------------------------------------------------- /* func UrlEncoded(str ssortingng) (ssortingng, error) { u, err := url.Parse(str) if err != nil { return "", err } return u.Ssortingng(), nil } // http://stackoverflow.com/questions/13820280/encode-decode-urls // import "net/url" func old_main() { a,err := UrlEncoded("hello world") if err != nil { fmt.Println(err) } fmt.Println(a) // https://gobyexample.com/url-parsing //s := "postgres://user:pass@host.com:5432/path?k=v#f" s := "postgres://user:pass@host.com:5432/path?k=vbla%23fooa#f" u, err := url.Parse(s) if err != nil { panic(err) } fmt.Println(u.RawQuery) fmt.Println(u.Fragment) fmt.Println(u.Ssortingng()) m, _ := url.ParseQuery(u.RawQuery) fmt.Println(m) fmt.Println(m["k"][0]) } */ // -------------------------------------------------------