小编典典

编码/解码 URL

go

在 Go 中编码和解码整个 URL 的推荐方法是什么?我知道方法url.QueryEscapeurl.QueryUnescape,但它们似乎并不是我正在寻找的。具体来说,我正在寻找像 JavaScriptencodeURIComponentdecodeURIComponent.


阅读 177

收藏
2021-12-21

共1个答案

小编典典

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

这是一个例子(play

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"
2021-12-21