Base64 Encoding in Go
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))
Previous Article
Next Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go