DEV Community

Kiran Krishnan
Kiran Krishnan

Posted on • Edited on • Originally published at kirandev.com

How to Base64 encode and decode data in Golang

In this post, I'll show you Base64 encoding and decoding in Golang.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that are designed to deal with ASCII.

This is to ensure that the data remain intact without modification during transport.

Read more about the Base64 encoding scheme here.

Golang provides built-in support for base64 encoding and decoding with a package encoding/base64.

Let's see the code for base64 encoding and decoding in Golang.

Create a new folder called base64-encode-decode.

mkdir base64-encode-decode

cd base64-encode-decode

touch main.go
Enter fullscreen mode Exit fullscreen mode

Open the main.go and import the necessary packages.

package main

import (
    "encoding/base64"
    "fmt"
)
Enter fullscreen mode Exit fullscreen mode

The package encoding/base64 provides 2 functions for encoding and decoding data in Base64 format.

EncodeToString encodes the passed data in Base64 format and returns the encoded data as a string.

func (enc *Encoding) EncodeToString(src []byte) string
Enter fullscreen mode Exit fullscreen mode

DecodeString decodes the passed data (string) and returns the decoded data as a byte slice.

func (enc *Encoding) DecodeString(s string) ([]byte, error)
Enter fullscreen mode Exit fullscreen mode

Let's add the code to encode and print the encoded data.

func main() {
    text := "Hello World - Go!"

    encodedText := base64.StdEncoding.EncodeToString([]byte(text));

    fmt.Printf("Encoded Text: %s\n", encodedText)
}
Enter fullscreen mode Exit fullscreen mode

The above code will print the following output:

Encoded Text: SGVsbG8gV29ybGQgLSBHbyE=
Enter fullscreen mode Exit fullscreen mode

Now, let's add the code to decode the encoded data and print the decoded data.

decodedText, err := base64.StdEncoding.DecodeString(encodedText);
if err != nil {
    panic(err)
}

fmt.Printf("Decoded Text: %s\n", decodedText)
Enter fullscreen mode Exit fullscreen mode

The above code will print the following output:

Decoded Text: Hello World - Go!
Enter fullscreen mode Exit fullscreen mode

Here is the complete working code.

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    text := "Hello World - Go!"

    encodedText := base64.StdEncoding.EncodeToString([]byte(text));

    fmt.Printf("Encoded Text: %s\n", encodedText)

    decodedText, err := base64.StdEncoding.DecodeString(encodedText);
    if err != nil {
        panic(err)
    }

    fmt.Printf("Decoded Text: %s\n", decodedText)
}
Enter fullscreen mode Exit fullscreen mode

I hope you found this article insightful.


👉 My blog kirandev.com

👉 Follow me on Twitter

👉 Find me on Github

Top comments (1)

Collapse
 
slimpython profile image
Abhi Raj

❤️👍