Home > Backend Development > Golang > Use the encoding/base64.StdEncoding function in the Go language documentation to implement Base64 encoding

Use the encoding/base64.StdEncoding function in the Go language documentation to implement Base64 encoding

王林
Release: 2023-11-03 10:05:13
Original
1249 people have browsed it

Use the encoding/base64.StdEncoding function in the Go language documentation to implement Base64 encoding

Base64 encoding is an encoding method that converts raw data into readable strings and is widely used in computer networks. In the Go language, you can use the encoding/base64.StdEncoding function to implement Base64 encoding. The specific code examples are as follows:

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    // 定义一个原始数据
    data := []byte("Hello, world!")

    // 使用StdEncoding进行Base64编码
    encData := base64.StdEncoding.EncodeToString(data)
    fmt.Println(encData)

    // 使用StdEncoding进行Base64解码
    decData, err := base64.StdEncoding.DecodeString(encData)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(decData))
}
Copy after login

In the above code, a raw data data is first defined, This data is then Base64 encoded using the base64.StdEncoding.EncodeToString() function and the result is stored in the variable encData. Then use the base64.StdEncoding.DecodeString() function to Base64 decode encData and store the result in the variable decData. Finally, use the fmt.Println() function to print out the encoded and decoded results.

In actual use, Base64 encoding is often used to convert binary data into readable strings. For example, it is often used in scenarios such as sending attachments in mailboxes and using HTTP to transfer files. The encoding/base64 package provided in the Go language provides convenient and easy-to-use Base64 encoding and decoding functions. Developers can flexibly use these functions to achieve their own needs.

The above is the detailed content of Use the encoding/base64.StdEncoding function in the Go language documentation to implement Base64 encoding. 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