Base64 is a binary-to-text encoding scheme. It encodes binary data in a printable ASCII string format. It is commonly used when there is a need to transmit binary data over a communication medium that do not correctly handle binary data and is designed to deal with textual data only.
Go provides built-in support for Base64 encoding and decoding. In this article, you’ll learn how to do Base64 encoding and decoding in Go.
Base64 Encoding in Go
Go’s encoding/base64 package supports both Standard as well as URL-compatible base64 encoding and decoding. The URL-compatible base64 encoding allows you to place the Base64 encoded string safely inside a URL.
Let’s look at an example:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := "Gol@ng is Awesome?~"
// Standard Base64 Encoding
encodedData := base64.StdEncoding.EncodeToString([]byte(data))
fmt.Println(encodedData)
// URL and filename-safe Base64 encoding
urlSafeEncodedData := base64.URLEncoding.EncodeToString([]byte(data))
fmt.Println(urlSafeEncodedData)
}
R29sQG5nIGlzIEF3ZXNvbWU/fg==
R29sQG5nIGlzIEF3ZXNvbWU_fg==
Base64 Encoding without padding
If you want to do raw, unpadded base64 encoding, then you can use RawStdEncoding
and RawURLEncoding
. These are same as StdEncoding and URLEncoding but omit the padding character. Note that, for all practical purposes, you should just use the padded base64 encoding as described in the above example.
Here is an example of unpadded Base64 encoding:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
data := "Gol@ng is Awesome?~"
// Standard Base64 Encoding without padding
encodedDataWithoutPadding := base64.RawStdEncoding.EncodeToString([]byte(data))
fmt.Println(encodedDataWithoutPadding)
// URL and filename-safe Base64 encoding without padding
urlSafeEncodedDataWithoutPadding := base64.RawURLEncoding.EncodeToString([]byte(data))
fmt.Println(urlSafeEncodedDataWithoutPadding)
}
# Output
R29sQG5nIGlzIEF3ZXNvbWU/fg
R29sQG5nIGlzIEF3ZXNvbWU_fg
Base64 Decoding in Go
The following example shows how to decode a Base64 encoded string in Go:
package main
import (
"encoding/base64"
"fmt"
)
func main() {
encodedData := "R29sQG5nIGlzIEF3ZXNvbWU/fg=="
// Standard Base64 Decoding
decodedData, err := base64.StdEncoding.DecodeString(encodedData)
if err != nil {
fmt.Printf("Error decoding Base64 encoded data %v", err)
}
fmt.Println(string(decodedData))
// URL and filename-safe Base64 decoding
urlSafeBase64EncodedData := "R29sQG5nIGlzIEF3ZXNvbWU_fg=="
urlSafeData, err := base64.URLEncoding.DecodeString(urlSafeBase64EncodedData)
if err != nil {
fmt.Printf("Error decoding Base64 encoded data %v", err)
}
fmt.Println(string(urlSafeData))
}
Gol@ng is Awesome?~
Gol@ng is Awesome?~