Access Environment Variables in Go

Environment variables are an easy way to pass configuration settings to your program. This allows you to not store sensitive config settings like database passwords or API keys in your code or local files. This is the way Heroku passes any configuration variables to your application.

To read/write environment variables, Go has three functions in the os package.

Parsing Date and Time in Go

Parsing a string containing date and time is one common task any programmer would encounter. It is also one of the most frustrating one, if you can’t remember the specific format string correctly (is if %b or %B?).

Go does datetime parsing slightly differently. Instead of having cryptic format strings, go uses something called layouts. There is one special date that you need to remember whenever you need to parse dates in go.

Mon Jan 2 15:04:05 MST 2006

Why this specific date?

How to create temporary files in go

When programming in python, one of the common modules I used often is the tempfile module. This module contains functions which create temporary files and returns a file object. This is useful if you are downloading large files and want to cleanup automatically once you are done.

Go has similar functions. Lets look at a sample code which create temporary folders and files and writes to it.

How to download files in Go

The best way to learn a new programming language is to write small utility programs. Let’s write one such program to download files via http in Go.

I am going to show the entire source code first and then walk through each section of it.

How to implement Singleton Pattern in Go

One of the most common design patterns that every developer needs to know is the Singleton Design pattern. Wikipedia defines Singleton Pattern as:

the singleton pattern is a software design pattern that restricts the instantiation of a class to one object.

To translate that in Go, whenever any goroutine tries to access an instance of a variable, you should get the same variable.

There are various ways to implement the singleton pattern in Go, but it is also quite easy to get it wrong. Let’s look at the different ways you can implement a singleton pattern and why most of them are wrong.