Base64 Encoding and Decoding in Golang: A Complete Guide

Base64 encoding is a technique used to encode binary data in a way that can be safely transmitted over the internet. In this article, we will walk through how to use the Go standard library to encode and decode base64 data.

Base64 Encoding

Base64 encoding takes binary data and encodes it into a format that consists of only printable ASCII characters. This allows the encoded data to be transmitted over systems that are designed to handle text data only, such as email systems.

To encode a string in Go, we can use the encoding/base64 package. Here's an example:

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    message := "Hello, world!"
    encoded := base64.StdEncoding.EncodeToString([]byte(message))
    fmt.Println(encoded)
}

In this example, we are using the StdEncoding function from the encoding/base64 package to encode the message "Hello, world!". The EncodeToString function takes a byte slice as input and returns a base64-encoded string.

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 a string in Go, we can use the encoding/base64 package. Here's an example:

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    encoded := "SGVsbG8sIHdvcmxkIQ=="
    decoded, err := base64.StdEncoding.DecodeString(encoded)
    if err != nil {
        fmt.Println("Error decoding string:", err)
        return
    }
    fmt.Println(string(decoded))
}

In this example, we are using the StdEncoding function from the encoding/base64 package to decode the encoded message "SGVsbG8sIHdvcmxkIQ==". The DecodeString function takes a base64-encoded string as an input and returns a byte slice of the decoded data. We are then using the string function to convert the byte slice back into a string.

Conclusion

In this article, we walked through how to use the Go standard library to encode and decode base64 data. 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.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!