go - golang 中有 urlencode() 函数吗?

标签 go url urlencode

这个问题在这里已经有了答案:





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/

相关文章:

go - Go 的方式是 PutUint32 还是直接使用 >> 运算符?

C++ 命名管道客户端不会读取超过 4096 字节

linux - 如何从网址列表中提取电子邮件?

Javascript:在不刷新页面的情况下更改网址

c# - 浏览器将 URL 路径部分中的编码斜杠 (%2F) 转换为文字斜杠 (/)

algorithm - 在 Go 中实现 Nor Flip Flop 逻辑门

string - 二进制字符串转unicode

php - Azure Linux Web 应用程序直接从 URL 下载文件不起作用

django - urlencode 过滤器在 Django 模板中不起作用

python - 在 Python 中将 & 转换为 &