编码/解码URL [英] Encode / decode URLs

查看:164
本文介绍了编码/解码URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go中的完整网址编码和解码的推荐方法是什么?我知道方法 url.QueryEscape url.QueryUnescape ,但它们似乎并不完全是我在寻找。具体来说,我正在寻找JavaScript的 encodeURIComponent decodeURIComponent 的方法。



谢谢。

解决方案

您可以使用 net / url 模块。它不会分解URL的各个编码功能,您必须让它构建整个URL。在源代码中有一个眯眼,我认为这是一个非常好的和符合标准的工作。



这是一个例子( playground link

  package main 

import(
fmt
net / url


func main(){

var url * url.URL
Url,err:= url.Parse(http://www.example.com)
如果err!= nil {
panic(boom )
}

Url.Path + =/ some / path / or / other_with_funny_characters?_or_not /
参数:= url.Values {}
参数。
parameters.Add(hello,54)
parameters.Add(vegetable,potato)
Url.RawQuery = parameters.Encode()

fmt.Printf(Encoded URL is%q\\\
,Url.String())
}

哪个打印

 编码的URL是http: //www.example.com/some/path/or/other_with_funny_c人物%3F_or_not /?蔬菜=土豆& hello = 42& hello = 54


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 don't seem to be exactly what I am looking for. Specifically I am looking for methods like JavaScript's encodeURIComponent and decodeURIComponent.

Thanks.

解决方案

You can do all the URL encoding you want with the net/url module. It doesn't break out the individual encoding functions for the parts of the URL, you have to let it construct the whole URL. Having had a squint at the source code I think it does a very good and standards compliant job.

Here is an example (playground link)

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.String())
}

Which prints

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

这篇关于编码/解码URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆