Golang URL编码解码

请问在Golang中如何进行URL的编码和解码操作?有哪些标准库函数可以使用?编码和解码时需要注意哪些特殊字符的处理?能否提供一个完整的示例代码?

2 回复

Golang中URL编码解码使用url.QueryEscapeurl.QueryUnescape函数。编码示例:url.QueryEscape("hello world")返回"hello%20world"。解码示例:url.QueryUnescape("hello%20world")返回"hello world"。注意处理可能的错误。

更多关于Golang URL编码解码的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在Golang中,URL编码和解码主要通过标准库的net/url包实现,使用QueryEscape/QueryUnescapePathEscape/PathUnescape函数。

1. URL查询参数编码/解码

  • 编码url.QueryEscape 将字符串编码为URL查询参数格式(如空格转为%20)。
  • 解码url.QueryUnescape 还原编码后的字符串。

示例代码

package main

import (
	"fmt"
	"net/url"
)

func main() {
	// 编码
	original := "hello world! @golang"
	encoded := url.QueryEscape(original)
	fmt.Println("Encoded:", encoded) // 输出:hello%20world%21%20%40golang

	// 解码
	decoded, err := url.QueryUnescape(encoded)
	if err != nil {
		panic(err)
	}
	fmt.Println("Decoded:", decoded) // 输出:hello world! @golang
}

2. URL路径编码/解码

  • 编码url.PathEscape 用于URL路径部分(保留斜杠/)。
  • 解码url.PathUnescape 对应解码。

示例代码

func main() {
	path := "path/with spaces&symbols"
	encodedPath := url.PathEscape(path)
	fmt.Println("Encoded Path:", encodedPath) // 输出:path%2Fwith%20spaces%26symbols

	decodedPath, err := url.PathUnescape(encodedPath)
	if err != nil {
		panic(err)
	}
	fmt.Println("Decoded Path:", decodedPath) // 输出:path/with spaces&symbols
}

注意事项:

  • 错误处理:解码时务必检查错误(如无效的编码格式)。
  • 应用场景
    • 查询参数:使用QueryEscape(表单数据、URL参数)。
    • 路径片段:使用PathEscape(处理URL路径部分)。
  • 特殊字符(如/?)在不同场景下编码规则不同。

通过这两个函数,可安全处理URL中的特殊字符,避免格式错误或安全漏洞。

回到顶部