Nono.MA

Deserialize a base64 string in Go

DECEMBER 10, 2022

I asked ChatGPT how to deserialize a base64 string in Golang.

Here's ChatGPT's output.

package main

import (
	"encoding/base64"
	"fmt"
)

func main() {
	// The base64 string you want to deserialize
	encodedString := "SGVsbG8sIHdvcmxkIQ=="

	// Decode the base64 string
	decodedBytes, err := base64.StdEncoding.DecodeString(encodedString)
	if err != nil {
		fmt.Println("Error decoding base64 string:", err)
		return
	}

	// Convert the decoded bytes to a string and print it
	decodedString := string(decodedBytes)
	fmt.Println(decodedString)
}

This code will print "Hello, world!" to the console.

In this example, we use the base64.StdEncoding type to decode the base64 string. This type is part of the encoding/base64 package, which provides functions for working with base64 strings in Go.

First, we use the DecodeString method to decode the base64 string and store the result in a variable called decodedBytes. This method returns a byte slice containing the decoded data, and an error value.

Next, we convert the decodedBytes slice to a string using the string function. This allows us to print the decoded string to the console.

If any errors occur during the decoding process, we print the error message and return from the function. Otherwise, the decoded string will be printed to the console.

Blog