/ Golang

Golang: Reading from Files and Writing to Disk with Golang

Today we will create a very basic application to read content from a file, and write the content from the file back to disk, but to another filename.

Basically, doing a copy of the file to another filename.

Golang Environment: Golang Docker Image

Dropping into a Golang Environment using Docker:

$ docker run -it golang:alpine sh

Our Golang Application

After we are in our container, lets write our app:

package main

import (

func main() {

    content, error := ioutil.ReadFile("source-data.txt")
    if error != nil {

    error = ioutil.WriteFile("destination-data.txt", content, 0644)
    if error != nil {

Building our application to a binary:

$ go build app.go

Creating our source-data.txt :

$ echo "foo" > source-data.txt

Running the Golang App:

When we run this app, it will read the content of source-data.txt and write it to destination-data.txt:

$ ./app.go

We can see that the file has been written to disk:

$ ls | grep data

Making sure the data is the same, we can do a md5sum hash function on them:

$ md5sum source-data.txt
d3b07384d113edec49eaa6238ad5ff00  source-data.txt

$ md5sum destination-data.txt
d3b07384d113edec49eaa6238ad5ff00  destination-data.txt


This was a very static way of doing it, as you need to hardcode the filenames. In the next post I will show how to use arguments to make it more dynamic.