Chances are, you do not need an introduction to base66 encoding. It is one of the most popular encoding/decoding methods used in programming. Go knows this and supports encoding and decoding of bas64 out of the box.
Using this tutorial, you will learn to encode and decode information from and to base64.
What is Base64?
Base64 is a byte-to-text encoding scheme used to represent binary data into an ASCII string format using radix-64 representation. This means that it utilizes a symbol table of 64 characters, including alphanumeric characters, +, /, and = symbols. Base64 will use only Alphanumeric characters and the three symbols to encode the provided data.
As mentioned, Base46 is one of the most used encoding formats to date. This is because it is simple, quick, and it just works.
What is Encoding/Decoding?
Encoding refers to a method of converting information from one form to another in a way that is reversible. Unlike encryption, encoding allows encoded information to be converted to the original format using the original encoding algorithm. Encryption, especially secure ones, does not allow information to be reverted to its original format. This makes it very useful in secure-dependent operations.
Decoding is the method of converting encoded information back to its original format.
Golang Base64 Encoding
In Go, base64 encoding is provided by the encoding/base64 package. Before use, we need to import it as shown:
Once imported, we can start encoding and decoding base64 information.
Golang Base64 Encode
To convert a string to base64 in Go, we need to convert it into a slice of bytes. We can illustrate this using an example:
import (
"encoding/base64"
"fmt"
)
func main() {
str := "Linuxhint"
encoded := base64.StdEncoding.EncodeToString([]byte(str))
fmt.Println("Base64: ", encoded)
}
We need to convert the string into a byte slice as the encoder requires a byte.
The resulting base64 string is as shown:
Golang Base64 Decode
Decoding is as simple as encoding. You pass the base64 string to the encoder, and it “spits” out your original string.
The example below illustrates this:
import (
"encoding/base64"
"fmt"
"log"
)
func main() {
b64_str := "TGludXhoaW50"
str, err := base64.StdEncoding.DecodeString(b64_str)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(str))
}
In this example, we convert a base64 string to the original string using the StdEncoding.DecodeString method.
Keep in mind that this method returns a slice of bytes. Hence, we need to cast it back to a string. The resulting output is as shown:
Conclusion
This article covered how to perform encode and decode data to and from base64 using the Go encoding/base64 package.
Thanks for Reading & Stay tuned for more Go tutorials.