Golang base64 encoding/decoding
Golang provides built-in support for base64 encoding/decoding in the package encoding/base64.
Syntax
Commonly used methods for encoding and decoding:
- Encoding:
func (enc *Encoding) EncodeToString(src []byte) string
EncodeToString takes a byte
- Decoding:
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 names
Example
Here 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/base64package, check out the official docs.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved