How to decode files in Go

Overview

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.

Example

package main
import (
"encoding/base64"
"io"
"os"
)
var b64 = `TWFuIGlzIGRpc3Rpbmd1aXNoZWQsIG5vdCBvbmx5IGJ5IGhpcyByZWFzb24sIGJ1dCBieSB0aGlz
IHNpbmd1bGFyIHBhc3Npb24gZnJvbSBvdGhlciBhbmltYWxzLCB3aGljaCBpcyBhIGx1c3Qgb2Yg
dGhlIG1pbmQsIHRoYXQgYnkgYSBwZXJzZXZlcmFuY2Ugb2YgZGVsaWdodCBpbiB0aGUgY29udGlu
dWVkIGFuZCBpbmRlZmF0aWdhYmxlIGdlbmVyYXRpb24gb2Yga25vd2xlZGdlLCBleGNlZWRzIHRo
ZSBzaG9ydCB2ZWhlbWVuY2Ugb2YgYW55IGNhcm5hbCBwbGVhc3VyZS4=`
func main() {
dec, err := base64.StdEncoding.DecodeString(b64)// decode string
if err != nil {
panic(err)
}
f, err := os.Create("myfilename")// create a file
if err != nil {
panic(err)
}
defer f.Close()
if _, err := f.Write(dec); err != nil {// write the decoded string to the new file
panic(err)
}
if err := f.Sync(); err != nil {
panic(err)
}
// got to the begginng of file
f.Seek(0, 0)
// output file contents
io.Copy(os.Stdout, f)
}

Explanation

  • 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.

Free Resources