What is the “encoding/base64” in Golang

Golang encoding/base64 package provides “functions to encode and decode data using the Base64 encoding scheme”. The Base64 is a binary-to-text encoding scheme commonly used to represent binary data in an ASCII string format. This can be helpful when you need to transmit binary data, such as images or encrypted content, in a text format, for example, in JSON or XML payloads or for embedding data in URLs.

Example

package main

import (
  "encoding/base64"
  "fmt"
)

func main() {
  // Original data
  data := []byte("Homer Simpson")

  // Encode the data using Base64
  encodedData := base64.StdEncoding.EncodeToString(data)
  fmt.Println("Encoded data:", encodedData)

  // Decode the Base64 encoded data
  decodedData, err := base64.StdEncoding.DecodeString(encodedData)
  if err != nil {
    fmt.Println("Error decoding data:", err)
    return
  }

  fmt.Println("Decoded data:", string(decodedData))
}

Output

Encoded data: SG9tZXIgU2ltcHNvbg==
Decoded data: Homer Simpson

In this code, we imported the “encoding/base64” package and used the EncodeToString() function to encode the original data (Homer Simpson) as a Base64 string.

In the next step, we used the “DecodeString()” function to decode the Base64 encoded data back to the original format. Finally, both the encoded and decoded data are printed to the console.

The base64.StdEncoding object used in the example represents the standard Base64 encoding defined in RFC 4648. However, there’s also an alternative URL-compatible encoding available as base64.URLEncoding, which uses a different set of characters to make the resulting Base64 string safe for use in URLs and filenames.

To use base64.URLEncoding, simply replaces base64.StdEncoding with base64.URLEncoding in the example above.

Leave a Comment