While creating an application, the need to decode an encoded file is inevitable. In this shot, we will learn how to decode a base64 encoded file with the help of an example. We will work with the encoded string value and decode it for practicability.
package mainimport ("encoding/base64""io""os")var b64 = `TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlzIHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2YgdGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGludWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRoZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=`func main() {dec, err := base64.StdEncoding.DecodeString(b64)// decode stringif err != nil {panic(err)}f, err := os.Create("myfilename")// create a fileif err != nil {panic(err)}defer f.Close()if _, err := f.Write(dec); err != nil {// write the decoded string to the new filepanic(err)}if err := f.Sync(); err != nil {panic(err)}// got to the begginng of filef.Seek(0, 0)// output file contentsio.Copy(os.Stdout, f)}
In lines 3-7, we import three packages:
encoding/base64
: We use this for decoding.
io
: We use this to get the file.
os
: We use this to process the file we get.
import ("encoding/base64""io""os")
Line 9: b64
is the variable where we save the encoded file we will decode.
Line 16: We decode the file using the base64
package.
Line 21: We create a file using os.Create()
.
Line 30: We write in the file using the f.Write(dec)
. After using the write()
method, we use the sync()
method.
Line 35: We access the file and start reading from the beginning. This is because it’s a text encoded file.
Line 38: We generate output from the decoded text file.