Encoding can convert data into another format understandable by a recipient. In this shot, we will learn to encode a simple string of letters with a code example.
package mainimport (b64 "encoding/base64""fmt")func main() {data := []byte("abc123!?$*&()'-=@~")sEnc := b64.StdEncoding.EncodeToString(data)fmt.Println(sEnc)}
In the above example, we import the required packages for the encoding process:
import (
b64 "encoding/base64"
"fmt"
)
b64
is our major package for carrying out the encoding.
fmt
is the package we use to print to the screen.
In our main function:
Line 10: We assign a variable data to a string of random characters and convert the string to a byte []byte("abc123!?$*&()'-=@~")
type since that data type the encode works with.
Line 12: We chain the b64
to methods(StdEncoding.EncodeToString
) that encode our parsed string of random characters.