0.00

Base64 Encode / Decode in Go Lang

How to encode or decode a string for Go Lang using the Base64 algorithm


programming language: go lang 1.8 or later
operating system: any
Updated:


Method definition: Base64 Encode - String

import (
	"encoding/base64"
)

func Base64Encode(data string) string {

	return base64.StdEncoding.EncodeToString([]byte(data))

}



Method definition: Base64 Decode - String

import (
	"encoding/base64"
	"log"
)

func Base64Decode(data string) string {

	// require to call here a `defer panic handler` before decoding the string with base64 because Go language may panic with malformed data !

	decoded, err := base64.StdEncoding.DecodeString(data)
	if(err != nil) {
		log.Println("[NOTICE] Base64Decode: ", err)
		//return "" // hint: be flexible, don't return here, try to decode as much as possible to have the same functionality as in Javascript / PHP or other languages ...
	} //end if

	return string(decoded)

}



Notice
The most efficient coding practices in Go language is to use byte[] instead of string as both input and output. Also take in consideration that converting too many times between string and byte[] and/or vice-versa is also not efficient when talking about a real project. But there are cases when you can use directly string thus the above methods became easy to use in that scenario.