〰️ Encode to and decode from Base64 strings in Golang

March 25, 2021
base64 encoding decoding strings

In this example, you learn how to encode and decode strings using Base64. The Base64 encoding takes binary data and turns it into text, making it more easily transmitted in text-based formats like JSON or HTML forms.

package main

import (
    "encoding/base64"
    "fmt"
)

func main() {
    text := "hello from gosamples.dev base64 encoding/decoding example!"
    // encoding
    encodedText := base64.StdEncoding.EncodeToString([]byte(text))
    fmt.Printf("Encoded text: %s\n", encodedText)

    // decoding
    rawDecodedText, err := base64.StdEncoding.DecodeString(encodedText)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Decoded text: %s\n", rawDecodedText)
}

To do this we need standard library encoding/base64 package which contains EncodeToString and DecodeToString methods. EncodeToString takes a byte array and returns an encoded string. DecodeToString needs an encoded string argument and returns a decoded byte array (and error).

Result:

Encoded text: aGVsbG8gZnJvbSBnb3NhbXBsZXMuZGV2IGJhc2U2NCBlbmNvZGluZy9kZWNvZGluZyBleGFtcGxlIQ==
Decoded text: hello from gosamples.dev base64 encoding/decoding example!

🙌 Case-insensitive string comparison in Go

Learn how to compare strings in a case-insensitive manner
introduction strings

🏁 Check if a string starts with a substring in Go

Learn how to use strings.HasPrefix() function
introduction strings

🪓 Split a string in Go

Learn how to split a string by comma or any other separator in Go
introduction strings