Base64 Encode & Decode in Go
Encode or decode below — it runs locally in your browser — then grab the canonical Go code. Go's standard-library encoding/base64 package gives you several encodings behind one API: StdEncoding, URLEncoding, and RawURLEncoding.
Encode and decode a string
Convert the string to a []byte, encode it, and on the way back check the error before using the result:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
// Encode
encoded := base64.StdEncoding.EncodeToString([]byte("Hello, world!"))
fmt.Println(encoded) // SGVsbG8sIHdvcmxkIQ==
// Decode
decoded, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
panic(err)
}
fmt.Println(string(decoded)) // Hello, world!
}
Tip: DecodeString returns ([]byte, error) — always check the error. Malformed input (bad characters or wrong padding) gives a non-nil error instead of panicking.
URL-safe Base64
For JWTs, URLs, and filenames, use the URL-safe alphabet (- and _ instead of + and /). RawURLEncoding omits padding, which is what JWTs expect:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("a+b/c=d")
// URL-safe, padded
fmt.Println(base64.URLEncoding.EncodeToString(data))
// URL-safe, no padding (JWT-style)
encoded := base64.RawURLEncoding.EncodeToString(data)
fmt.Println(encoded)
// Decode with the matching decoder
decoded, _ := base64.RawURLEncoding.DecodeString(encoded)
fmt.Println(string(decoded))
}
Encode bytes / files
Read the file into a byte slice with os.ReadFile, then encode it like any other []byte:
package main
import (
"encoding/base64"
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("image.png")
if err != nil {
panic(err)
}
encoded := base64.StdEncoding.EncodeToString(data)
// As a data URI for HTML/CSS:
fmt.Println("data:image/png;base64," + encoded)
}
Frequently asked questions
How do I Base64 encode a string in Go?
Convert it to a byte slice and encode: base64.StdEncoding.EncodeToString([]byte("Hello, world!")) returns "SGVsbG8sIHdvcmxkIQ==".
How do I Base64 decode in Go?
base64.StdEncoding.DecodeString(s) returns ([]byte, error); check the error, then use string(decoded) for text.
What is the difference between StdEncoding and URLEncoding?
StdEncoding uses + and /; URLEncoding uses - and _; RawURLEncoding is URL-safe with no padding.
How do I do URL-safe Base64?
Use base64.URLEncoding (padded) or base64.RawURLEncoding (no padding, for JWTs), and decode with the matching decoder.
Need image, file, or URL-safe modes?
The main base64.dev tool handles text, images, files, and URL-safe Base64 with auto-detect.
Open base64.dev →