这个问题在这里已经有了答案:
Encode / decode URLs
(8 个回答)
1年前关闭。
许多语言,例如 JavaScript 和 PHP,都有一个 urlencode()
可用于对查询字符串参数的内容进行编码的函数。
"example.com?value=" + urlencode("weird string & number: 123")
这确保了
&
, %
、空格等进行编码,以便您的 URL 保持有效。我看到 golang 提供了一个 URL 包,它有一个 Encode() function用于查询字符串值。这很好用,但在我的情况下,它需要我解析 URL,我宁愿不这样做。
我的 URL 是由客户端声明的,不会更改顺序,并且可能会影响潜在的重复参数(这是 URL 中的合法内容)。所以我使用
Replace()
像这样:func tweak(url string) string {
url.Replace("@VALUE@", new_value, -1)
return url
}
@VALUE@
预计用作查询字符串参数的值,如下所示:example.com?username=@VALUE@
所以,我想做的是:
url.Replace("@VALUE@", urlencode(new_value), -1)
在 Golang 中是否有这样一个易于访问的功能?
最佳答案
是的,你可以在这里使用这些函数来做到这一点:
package main
import (
"encoding/base64"
"fmt"
"net/url"
)
func main() {
s := "enc*de Me Plea$e"
fmt.Println(EncodeParam(s))
fmt.Println(EncodeStringBase64(s))
}
func EncodeParam(s string) string {
return url.QueryEscape(s)
}
func EncodeStringBase64(s string) string {
return base64.StdEncoding.EncodeToString([]byte(s))
}
关于go - golang 中有 urlencode() 函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58419348/