在Go中,可以使用net/url包中的Escape
和Unescape
函数来处理URL中的特殊字符。
Escape
函数将URL编码为字符串,以便在URL中使用特殊字符,例如空格、&和/。例如:
package main
import (
"fmt"
"net/url"
)
func main() {
s := "Hello, World! & Goodbye/Space"
fmt.Println(url.QueryEscape(s))
}
输出:
Hello%2C+World%21+%26+Goodbye%2FSpace
Unescape
函数将编码后的URL字符串解码为原始字符串。例如:
package main
import (
"fmt"
"net/url"
)
func main() {
s := "Hello%2C+World%21+%26+Goodbye%2FSpace"
decoded, _ := url.QueryUnescape(s)
fmt.Println(decoded)
}
输出:
Hello, World! & Goodbye/Space