Golang Base64 Encode and Decode Example using StdEncoding



In this source code example, we will demonstrate how to use base64.StdEncoding to encode and decode a string in Golang.

Golang provides built-in support for base64 encoding/decoding in the package encoding/base64.

Golang StdEncoding Encoding and Decoding Example

Here is an example of encoding and then decoding the string, “source code examples” using base64 encoding with StdEncoding.


package main

import (
    "encoding/base64"
    "fmt"
)

func main() {

    // String to encode
    str := "Source code examples"

    // base64.StdEncoding: Standard encoding with padding
    // It requires a byte slice so we cast the string to []byte
    encodedStr := base64.StdEncoding.EncodeToString([]byte(str))
    fmt.Println("Encoded:", encodedStr)

    // Decoding may return an error, in case the input is not well formed
    decodedStr, err := base64.StdEncoding.DecodeString(encodedStr)
    if err != nil {
        panic("malformed input")
    }
    fmt.Println("Decoded:", string(decodedStr))
}	

Output:

Encoded: U291cmNlIGNvZGUgZXhhbXBsZXM=
Decoded: Source code examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments