小编典典

编码/解码URL

go

在Go中编码和解码整个URL的推荐方法是什么?我知道的方法url.QueryEscapeurl.QueryUnescape,但他们似乎并没有被正是我期待的。具体来说,我正在寻找JavaScript
encodeURIComponent和之类的方法decodeURIComponent

谢谢。


阅读 542

收藏
2020-07-02

共1个答案

小编典典

您可以使用net /
url
模块进行所有想要的URL编码。它不会分解URL各个部分的单独编码功能,您必须让它构造整个URL。斜视了源代码后,我认为它做得很好并且符合标准。

这是一个示例(游乐场链接

package main

import (
    "fmt"
    "net/url"
)

func main() {

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

哪些印刷品

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