Golang provides built-in support for base64 encoding/decoding in the package encoding/base64
.
Commonly used methods for encoding and decoding:
func (enc *Encoding) EncodeToString(src []byte) string
EncodeToString
takes a byte
func (enc *Encoding) DecodeString(s string) ([]byte, error)
DecodeString
takes a base64 encoded string and returns the decoded data as a byte slice. It will also return an error in case the input string has invalid base64 data.
The types of encoding available are:
StdEncoding
: standard base64 encodingURLEncoding
: alternate base64 encoding used in URLs and file namesRawStdEncoding
: standard, raw, unpadded base64 encodingRawURLEncoding
: unpadded alternate base64 encoding for URLs and file namesHere is an example of encoding and then decoding the string, “Hello World!” using base64 encoding with StdEncoding
.
package mainimport ("encoding/base64""fmt")func main() {// String to encodestr := "Hello World!"// base64.StdEncoding: Standard encoding with padding// It requires a byte slice so we cast the string to []byteencodedStr := base64.StdEncoding.EncodeToString([]byte(str))fmt.Println("Encoded:", encodedStr)// Decoding may return an error, in case the input is not well formeddecodedStr, err := base64.StdEncoding.DecodeString(encodedStr)if err != nil {panic("malformed input")}fmt.Println("Decoded:", string(decodedStr))}
For more information on the methods available as part of the
encoding/base64
package, check out the official docs.