Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

encode
base64
golang
communitycreator

How to encode in base64 using Golang

Chinweuba Elijah Azubuike

Overview

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.

Example

package main

import (
    b64 "encoding/base64"
    "fmt"
)

func main() {

    data := []byte("abc123!?$*&()'-=@~")

    sEnc := b64.StdEncoding.EncodeToString(data)
    fmt.Println(sEnc)

   
}

Explanation

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:

  1. 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.

  2. Line 12: We chain the b64 to methods(StdEncoding.EncodeToString) that encode our parsed string of random characters.

RELATED TAGS

encode
base64
golang
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring