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