golang 中有 urlencode() 函数吗?

Ale*_*lke 7 url urlencode go

许多语言,例如 JavaScript 和 PHP,都有一个urlencode()函数,可以用来对查询字符串参数的内容进行编码。

"example.com?value=" + urlencode("weird string & number: 123")
Run Code Online (Sandbox Code Playgroud)

这可确保对&%、 空格等进行编码,以便您的 URL 保持有效。

我看到 golang 提供了一个 URL 包,它有一个用于查询字符串值Encode() 函数。这很好用,但在我的情况下,它需要我解析 URL,我宁愿不这样做。

我的 URL 是由客户端声明的,不会更改顺序,并且可能会影响潜在的重复参数(这是 URL 中的合法内容)。所以我使用Replace()这样的:

func tweak(url string) string {
  url.Replace("@VALUE@", new_value, -1)
  return url
}
Run Code Online (Sandbox Code Playgroud)

@VALUE@有望被用作查询字符串参数中的值:

example.com?username=@VALUE@
Run Code Online (Sandbox Code Playgroud)

所以,我想做的是:

  url.Replace("@VALUE@", urlencode(new_value), -1)
Run Code Online (Sandbox Code Playgroud)

在 Golang 中是否有这样一个易于访问的功能?

Fra*_*ias 16

是的,你可以在这里使用这些函数来做到这一点:

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))
}
Run Code Online (Sandbox Code Playgroud)