Base64 Encoding in Go
Golang Concepts
Go: Base64 Encoding
Base64 is a common method for encoding binary data as ASCII text. It is often used for transmitting data over media that only supports ASCII characters, such as email and HTML.
How to Encode in Go using Base64 Encoding?
In Go, you can encode a byte slice as Base64 using the standard library's encoding/base64 package. Here's an example of encoding a string:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
message := "Hello, world!"
encoded := base64.StdEncoding.EncodeToString([]byte(message))
fmt.Println(encoded)
}
// output
//SGVsbG8sIHdvcmxkIQ==
How to Decoding in Go using Base64?
To decode the encoded string back into its original form, you can use the DecodeString function:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
encoded := "SGVsbG8sIHdvcmxkIQ=="
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(string(decoded))
}
//output
//Hello, world!
You can also use other Base64 encoding variants provided by the encoding/base64 package. For example, URLEncoding uses a different set of characters that are safe to use in URLs:
encoded := base64.URLEncoding.EncodeToString([]byte(message))