Golang base64 encoding/decoding

Golang provides built-in support for base64 encoding/decoding in the package encoding/base64.

svg viewer

Syntax

Commonly used methods for encoding and decoding:

  1. Encoding:
func (enc *Encoding) EncodeToString(src []byte) string

EncodeToString takes a byte slicea dynamically-sized, flexible abstraction of array and returns a base64 encoding as a string.

  1. Decoding:
func (enc *Encoding) DecodeString(s string) ([]byte, error)

DecodeString takes a base64 encoded string and returns the decoded data as a byte slice. It will also return an error in case the input string has invalid base64 data.

The types of encoding available are:

  • StdEncoding: standard base64 encoding
  • URLEncoding: alternate base64 encoding used in URLs and file names
  • RawStdEncoding: standard, raw, unpadded base64 encoding
  • RawURLEncoding: unpadded alternate base64 encoding for URLs and file names

Example

Here is an example of encoding and then decoding the string, “Hello World!” using base64 encoding with StdEncoding.

package main
import (
"encoding/base64"
"fmt"
)
func main() {
// String to encode
str := "Hello World!"
// base64.StdEncoding: Standard encoding with padding
// It requires a byte slice so we cast the string to []byte
encodedStr := base64.StdEncoding.EncodeToString([]byte(str))
fmt.Println("Encoded:", encodedStr)
// Decoding may return an error, in case the input is not well formed
decodedStr, err := base64.StdEncoding.DecodeString(encodedStr)
if err != nil {
panic("malformed input")
}
fmt.Println("Decoded:", string(decodedStr))
}

For more information on the methods available as part of the encoding/base64 package, check out the official docs.

Copyright ©2024 Educative, Inc. All rights reserved