How to implement URL encoding in golang

PHPz
Release: 2023-04-24 16:56:59
Original
2589 people have browsed it

In recent years, with the development of Internet technology, more and more program developers have begun to use Go language for development. Go language is an efficient, fast, and safe programming language, and it also supports URL encoding. However, if you want to implement URL encoding yourself in Go, the following content will be helpful to you.

URL encoding is a way of converting special characters into something that can be accepted and transmitted by URLs. For non-ASCII characters such as spaces and Chinese characters, they are not allowed in URL addresses, so we need to encode them. In Go language, you can use the "net/url" package to implement URL encoding and decoding. The following is a sample code:

package main

import (
    "fmt"
    "net/url"
)

func main() {
    originalString := "https://www.example.com/path?foo=bar&baz=qux#anchor"
    encodedString := url.QueryEscape(originalString)
    decodedString, err := url.QueryUnescape(encodedString)

    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Original string:", originalString)
    fmt.Println("Encoded string:", encodedString)
    fmt.Println("Decoded string:", decodedString)
}
Copy after login

In the above code, we first define a URL address string originalString that needs to be encoded, and then call the "url.QueryEscape" function to encode it. Next, we decode the encoded string using the "url.QueryUnescape" function and save the result in the decodedString variable.

The output result of the above code is as follows:

Original string: https://www.example.com/path?foo=bar&baz=qux#anchor
Encoded string: https%3A%2F%2Fwww.example.com%2Fpath%3Ffoo%3Dbar%26baz%3Dqux%23anchor
Decoded string: https://www.example.com/path?foo=bar&baz=qux#anchor
Copy after login

As can be seen from the above output result, after encoding through the "url.QueryEscape" function, the original string is converted into encoded characters string, all non-ASCII characters are escaped into the form of "%XX". On the contrary, after decoding through the "url.QueryUnescape" function, the encoded string is restored to the original string.

In addition to using the "net/url" package, we can also implement URL encoding manually. The following is an example of manually implementing URL encoding:

package main

import (
    "fmt"
    "strings"
)

var encodeMap = map[byte]string{
    '!':  "%21",
    '#':  "%23",
    '$':  "%24",
    '&':  "%26",
    '\'': "%27",
    '(':  "%28",
    ')':  "%29",
    '*':  "%2A",
    '+':  "%2B",
    ',':  "%2C",
    '/':  "%2F",
    ':':  "%3A",
    ';':  "%3B",
    '=':  "%3D",
    '?':  "%3F",
    '@':  "%40",
    '[':  "%5B",
    ']':  "%5D",
}

func encode(s string) string {
    var b strings.Builder
    for i := 0; i < len(s); i++ {
        ch := s[i]
        if val, ok := encodeMap[ch]; ok {
            b.WriteString(val)
        } else {
            b.WriteByte(ch)
        }
    }
    return b.String()
}

func main() {
    originalString := "https://www.example.com/path?foo=bar&baz=qux#anchor"
    encodedString := encode(originalString)
    fmt.Println(encodedString)
}
Copy after login

In the above code, we first define an "encodeMap" variable, which contains the special characters that need to be escaped and the corresponding escape string. Then, we define an "encode" function to perform URL encoding. In the function, we traverse the string that needs to be encoded and determine whether each character is in the "encodeMap". If it exists, use the corresponding escape string to replace it; otherwise, output it as it is.

Through the above two methods, we can implement URL encoding and decoding in Go language. In particular, we can use the "net/url" package to implement shorter code and more comprehensive URL encoding rules, while manual implementation is relatively simple and easy to understand and suitable for small-scale encoding needs. In practical applications, the appropriate encoding method can be selected according to specific scenarios.

The above is the detailed content of How to implement URL encoding in golang. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!