How Do You Encode a String to Base64 in Go?
Use base64.StdEncoding.EncodeToString() to encode a byte slice to a Base64 string. Go strings convert to byte slices with []byte(). The StdEncoding variable uses the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) with = padding as defined in RFC 4648 Section 4.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
original := "Hello, World!"
encoded := base64.StdEncoding.EncodeToString([]byte(original))
fmt.Println(encoded) // SGVsbG8sIFdvcmxkIQ==
}
Go strings are UTF-8 by default, so []byte(original) produces UTF-8 bytes without requiring an explicit encoding conversion. The StdEncoding variable is a package-level *Encoding instance ready for immediate use. For a browser-based alternative, use the Base64 text encoder.
How Do You Decode Base64 in Go?
Use base64.StdEncoding.DecodeString() to convert a Base64 string back to a byte slice. This method returns two values: the decoded bytes and an error. Always check the error to handle invalid Base64 input. Convert the byte slice to a string with string().
package main
import (
"encoding/base64"
"fmt"
"log"
)
func main() {
decoded, err := base64.StdEncoding.DecodeString("SGVsbG8sIFdvcmxkIQ==")
if err != nil {
log.Fatal("Decode error:", err)
}
fmt.Println(string(decoded)) // Hello, World!
}
The error is of type base64.CorruptInputError and indicates the byte offset where the invalid character was found. Go's multiple return value pattern replaces try-catch exception handling with explicit error checking. To decode Base64 directly in your browser, use the Base64 text decoder.
What Base64 Encoding Types Does Go Provide?
Go's encoding/base64 package provides 4 predefined encoding variables. Each implements a different combination of alphabet and padding behavior. The standard and URL-safe variants each have a padded and an unpadded (raw) version.
| Variable | Alphabet | Padding | RFC |
|---|---|---|---|
StdEncoding | A-Z, a-z, 0-9, +, / | Yes (=) | RFC 4648 §4 |
URLEncoding | A-Z, a-z, 0-9, -, _ | Yes (=) | RFC 4648 §5 |
RawStdEncoding | A-Z, a-z, 0-9, +, / | No | RFC 4648 §3.2 |
RawURLEncoding | A-Z, a-z, 0-9, -, _ | No | RFC 4648 §3.2 |
The "Raw" variants omit = padding characters from the output. Use RawURLEncoding for JWT tokens and other contexts where padding is not expected. All four variables are safe for concurrent use by multiple goroutines. For a deeper understanding of these encoding variants, see the What is Base64 guide.
How Do You Use URL-Safe Base64 in Go?
Use base64.URLEncoding for URL-safe Base64 with padding, or base64.RawURLEncoding for URL-safe Base64 without padding. The URL-safe alphabet replaces + with - and / with _ to prevent conflicts in URLs and filenames. JWT tokens use RawURLEncoding.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := []byte("subjects?abcd")
// URL-safe with padding
withPad := base64.URLEncoding.EncodeToString(data)
fmt.Println(withPad) // c3ViamVjdHM_YWJjZA==
// URL-safe without padding (common for JWT)
noPad := base64.RawURLEncoding.EncodeToString(data)
fmt.Println(noPad) // c3ViamVjdHM_YWJjZA
}
Decode URL-safe strings with the matching encoding: URLEncoding.DecodeString() for padded input, RawURLEncoding.DecodeString() for unpadded input. Using the wrong encoding causes a CorruptInputError. The URL-safe Base64 tool provides browser-based encoding with the same alphabet.
How Do You Encode a File to Base64 in Go?
Read the file into a byte slice using os.ReadFile(), then pass the bytes to base64.StdEncoding.EncodeToString(). This approach loads the entire file into memory and works for files that fit within available RAM.
package main
import (
"encoding/base64"
"fmt"
"log"
"os"
)
func main() {
fileBytes, err := os.ReadFile("image.png")
if err != nil {
log.Fatal("File read error:", err)
}
encoded := base64.StdEncoding.EncodeToString(fileBytes)
// Create a data URI for HTML embedding
dataUri := "data:image/png;base64," + encoded
fmt.Println(dataUri)
}
For images, prepend the appropriate MIME type to create a data URI. The Base64 file encoder performs the same operation in your browser without uploading the file. To decode back to a file, use os.WriteFile() with the decoded byte slice.
How Do You Use Base64 Streaming in Go?
Use base64.NewEncoder() to create a streaming encoder that writes Base64 output to any io.Writer. Use base64.NewDecoder() to create a streaming decoder that reads from any io.Reader. These process data incrementally without loading entire files into memory.
package main
import (
"encoding/base64"
"io"
"log"
"os"
)
func main() {
// Encode a file using streaming
input, _ := os.Open("large-file.bin")
defer input.Close()
output, _ := os.Create("large-file.b64")
defer output.Close()
encoder := base64.NewEncoder(base64.StdEncoding, output)
io.Copy(encoder, input)
encoder.Close() // Flush remaining bytes and padding
// Decode a Base64 file using streaming
b64File, _ := os.Open("large-file.b64")
defer b64File.Close()
decoded, _ := os.Create("decoded-file.bin")
defer decoded.Close()
decoder := base64.NewDecoder(base64.StdEncoding, b64File)
io.Copy(decoded, decoder)
}
Always call encoder.Close() after writing to flush any buffered bytes and write the final padding. The decoder does not require closing. Stream-based encoders and decoders are not goroutine-safe. Use a separate encoder or decoder per goroutine. Learn more about Base64 encoding fundamentals in the What is Base64 guide.
How Do You Create a Custom Base64 Encoding in Go?
Use base64.NewEncoding() with a 64-character alphabet string to create a custom *Encoding instance. The alphabet string defines the mapping from 6-bit values (0-63) to characters. Call .WithPadding(base64.NoPadding) to disable padding, or provide a custom padding character.
package main
import (
"encoding/base64"
"fmt"
)
func main() {
// Custom alphabet (example: reordered standard alphabet)
const customAlphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210+/"
custom := base64.NewEncoding(customAlphabet)
encoded := custom.EncodeToString([]byte("Hello"))
fmt.Println(encoded) // Uses custom mapping
// Custom encoding without padding
noPad := base64.NewEncoding(customAlphabet).WithPadding(base64.NoPadding)
encoded2 := noPad.EncodeToString([]byte("Hello"))
fmt.Println(encoded2)
}
The alphabet string must contain exactly 64 unique ASCII characters. NewEncoding() panics if the alphabet is invalid. Custom encodings support all the same methods as predefined encodings: EncodeToString(), DecodeString(), NewEncoder(), and NewDecoder(). See the Base64 character table for the standard alphabet reference.
Frequently Asked Questions
What package provides Base64 in Go?
The encoding/base64 package in Go's standard library provides Base64 encoding and decoding. Import it with import "encoding/base64". The package includes 4 predefined encoding variables (StdEncoding, URLEncoding, RawStdEncoding, RawURLEncoding) and supports custom alphabets via base64.NewEncoding().
What is the difference between StdEncoding and RawStdEncoding in Go?
StdEncoding uses the standard Base64 alphabet (A-Z, a-z, 0-9, +, /) and adds = padding to make the output length a multiple of 4. RawStdEncoding uses the same alphabet but omits padding. Use RawStdEncoding when the consuming system does not require or expect padding characters.
Does Go support MIME Base64 encoding?
Go does not provide a built-in MIME encoder that inserts line breaks every 76 characters. Use StdEncoding for the encoding itself, then insert CRLF line breaks manually every 76 characters if MIME format (RFC 2045) is required. The mime and mime/multipart packages handle MIME messages but not raw Base64 line wrapping.
Is the encoding/base64 package goroutine-safe?
Yes. The predefined encoding variables (StdEncoding, URLEncoding, RawStdEncoding, RawURLEncoding) and any Encoding created by NewEncoding() are safe for concurrent use by multiple goroutines. The EncodeToString() and DecodeString() methods do not hold shared state. Stream-based encoders and decoders are not goroutine-safe and should not be shared between goroutines.
How does Go handle Base64 decoding errors?
DecodeString() returns two values: the decoded byte slice and an error. The error is of type base64.CorruptInputError, which indicates the byte offset where the invalid character was found. Always check the error return value. Go's multiple return value pattern eliminates the need for try-catch exception handling. Use the Base64 validator for quick browser-based validation.
Related Base64 Tools and Guides
- What is Base64? - Comprehensive guide to the Base64 encoding format
- Base64 Text Encoder - Encode text to Base64 in your browser
- Base64 File Encoder - Encode files to Base64 client-side
- URL-Safe Base64 Encoder - Encode with the URL-safe alphabet
- Base64 Character Table - Complete alphabet reference
- Base64 Validator - Validate Base64 strings instantly
- All Base64 Tools - Browse the complete toolset