Base64 Encoding and Decoding in Golang - Explained in Details
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.
Base64 Encoding
Base64 encoding is a technique used to encode binary data in a way that can be safely transmitted over the internet.
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==
Base64 Decoding
Base64 decoding takes the encoded data and decodes it back into its original binary form. This is useful for when we receive encoded data and need to use it in its original form.
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))
Conclusion
In this article, we learned how to use the Go standard library to encode and decode base64 data in golang. Base64 encoding is a useful technique for transmitting binary data over systems that are designed to handle text data only. By using the encoding/base64
package in Go, we can easily encode and decode base64 data in our programs.
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