Documentation ¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Encode ¶
Encode encodes a byte slice into a percent-encoded string. Each byte is converted to its corresponding percent-encoded representation using uppercase hexadecimal digits. This method does not perform any character encoding, but simply represents the raw bytes as percent-encoded.
func Other2Utf8 ¶
Other2Utf8 converts a percent-encoded string from a specific encoding (e.g., GBK) to a UTF-8 encoded string. This function is useful when working with URIs that have been percent-encoded using non-UTF-8 encodings. It takes the original encoded string and a decoder for the source encoding, returning the UTF-8 encoded result or an error if the input is malformed.
Example ¶
package main import ( "fmt" "net/url" go_percent_encoding "github.com/leoleaf/go-percent-encoding" "golang.org/x/text/encoding/simplifiedchinese" ) func main() { // assume the web server encoding is GBK // get the url from the web server urlFromServer := "http://www.example.com/register?age=19&name=%D5%C5%C8%FD" u, err := url.Parse(urlFromServer) if err != nil { fmt.Println(err) return } dec := simplifiedchinese.GBK.NewDecoder() u.RawQuery, err = go_percent_encoding.Other2Utf8(u.RawQuery, dec) if err != nil { fmt.Println(err) return } query := u.Query() fmt.Println(query.Get("age")) fmt.Println(query.Get("name")) }
Output: 19 张三
func Utf8ToOther ¶
Utf8ToOther converts a UTF-8 encoded, percent-encoded string to a string encoded with a different character encoding (e.g., GBK). This function is useful for generating URIs expected to be interpreted by systems that use non-UTF-8 encodings. It takes the UTF-8 encoded string and an encoder for the target encoding, returning the newly encoded result or an error if the input is malformed.
Example ¶
package main import ( "fmt" "net/url" go_percent_encoding "github.com/leoleaf/go-percent-encoding" "golang.org/x/text/encoding/simplifiedchinese" ) func main() { u, err := url.Parse("http://www.example.com/register") if err != nil { fmt.Println(err) return } // add query string query := u.Query() query.Add("age", "19") query.Add("name", "张三") u.RawQuery = query.Encode() fmt.Println(u.String()) // if the web server encoding is not utf-8, you need to encode the query string. // assume the web server encoding is GBK enc := simplifiedchinese.GBK.NewEncoder() targetUrl, err := go_percent_encoding.Utf8ToOther(u.String(), enc) if err != nil { fmt.Println(err) return } fmt.Println(targetUrl) }
Output: http://www.example.com/register?age=19&name=%E5%BC%A0%E4%B8%89 http://www.example.com/register?age=19&name=%D5%C5%C8%FD