Created
July 6, 2018 18:21
-
-
Save xeoncross/e83313ac7157c659416676a6044fcd1e to your computer and use it in GitHub Desktop.
Base 64 encode and decode a byte array in Golang. https://play.golang.org/p/X4z9zq0nXlW
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"encoding/base64" | |
) | |
func main() { | |
str := "Hello, playground :)" | |
b := Base64Encode([]byte(str)) | |
fmt.Printf("%q\n", b) | |
msg, err := Base64Decode(b) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("%q\n", msg) | |
} | |
func Base64Encode(message []byte) []byte { | |
b := make([]byte, base64.StdEncoding.EncodedLen(len(message))) | |
base64.StdEncoding.Encode(b, message) | |
return b | |
} | |
func Base64Decode(message []byte) (b []byte, err error) { | |
var l int | |
b = make([]byte, base64.StdEncoding.DecodedLen(len(message))) | |
l, err = base64.StdEncoding.Decode(b, message) | |
if err != nil { | |
return | |
} | |
return b[:l], nil | |
} |
Saved my day! Thanks
I am trying to Decode a base64 encoded byte array. But when I convert it to a string variable and pass it to DecodeString()
function, then it always gives me the CorruptInputError. But when I get the string value and pass it into the DecodeString()
function, then it does the decoding smoothly.
Any help is much appreciated...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks 👍
Maybe this would make sense as an example in the official docs? (the byte decoding)