Cookies management by TermsFeed Cookie Consent

👉 Encode a string to Base64 in Go

base64 encoding strings

To encode a string to Base64 in Go, use the EncodeToString() function from the encoding/base64 standard library package. This function takes a byte slice and converts it to a Base64 encoded string, but it can also be used for a string argument by converting it to a byte slice.

Check also how to decode Base64 to a string in Go.

package main

import (
    "encoding/base64"
    "fmt"
)

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

Output:

Encoded text: aGVsbG8gZnJvbSBnb3NhbXBsZXMuZGV2IGJhc2U2NCBlbmNvZGluZyBleGFtcGxlIQ==

The EncodeToString() is a method of StdEncoding which is an object representing the standard base64 encoding, as defined in RFC 4648.


Thank you for being on our site 😊. If you like our tutorials and examples, please consider supporting us with a cup of coffee and we'll turn it into more great Go examples.

Have a great day!

Buy Me A Coffee

👈 Decode Base64 to a string in Go

Learn how to decode Base64 data to a string using encoding/base64 package
base64 encoding strings

🧮 Sort a string slice containing numbers in Go

Learn how to sort strings with numbers in natural order
sort slice strings

🍒 Concatenate strings in Go

Learn the differences between string concatenation methods
introduction strings