Waiting for Goroutines to complete

Goroutines are one of the best features of Go language. It is very easy to run a function as a goroutine, you just have to use the keyword go before the function call.

Here is a very simple function which sleeps for n seconds and prints a line.

String Replacements in Go

In a previous post, we saw how we can use Regular expressions in Go to match and replace patterns in a string. While regexps are very useful, you might not want to them for every time you want to do some basic string manipulation. The strings package has few functions which works well for basic string replacement.

Let’s look at two such functions.

Creating errors in go

Go is a modern language, but doesn’t use try-except blocks to handle errors. Errors are simple values that can be returned from functions and it is common to check for errors before proceeding with your next steps. Let’s see the different ways to create your own errors in Go.

Any value is an error if it implements the error interface.

type error interface {
    Error() string
}

How to write benchmarks in Go

In the previous post, we saw how to write a simple unit test case and also how to write table driven test cases. In this post we will quickly see how to write benchmarks, as go supports running benchmarks on your functions as part of the standard testing package.

Using these simple benchmarks, you can quickly examine your code’s performance. But do remember, that you would need a profiler to go in depth of which part of your code is causing the performance bottleneck.

Table Driven Unit Testing

Go has built-in support for writing test cases for your code. And it is important to write as much test cases as possible to make sure you cover all possible conditions. You have to use the testing standard package to write your unit test cases.

Let’s first see the simplest way to write test cases for your functions, then see how to test multiple conditions.

Regular Expressions in Go

Regular Expressions is one skill that is essential to any programmer. We deal with lot of unstructured data and regexps are one vital tool to parse and process it.

Regular Expressions - XKCD 208

Lets look at the different functions and methods available to construct and use regular expressions in Go. For this tutorial I am going to assume you know the basics of Regex.

Basic Logging in Go

Any application you write, should have proper logging to ensure you are able to monitor and identify problems in production. You can’t and shouldn’t run a debugger in a production environment and logs are the only proper way to get an idea of what is happening in your code.

Go has a native logging package called log. It has a standard Logger, which has helper functions to log messages and errors. The default Logger prints the date and time stamp of the logged error, which makes it much more useful than using fmt.Println

Accepting Variable Number of Arguments in a Function

Functions in Go are capable of accepting multiple number of arguments, also called as variadic functions. One prominent example of such a function is fmt.Println as you can pass in any number of variables, it will print each of them separated by a space.

Loading Application Config from Environment Variables

In a previous post, I had written how to read Environment Config. I had also mentioned how you can only store and retrieve string values. But if your application is trying to load config files from it, you would want to load the variables as integer or boolean values.

When I was new to go, I was using the strconv package to convert the string to various data types. Though it works, it isn’t a clean way to write your code.

Later, I found the envconfig package which loads a config object from environment variables, and my life was changed. The way to use envconfig is really simple.

Listing Files and Directories in Go

Next to reading/writing to files, learning how to list the different files and directories is very important. I used to use python for doing lot of string processing and the common way to store data is in the form of jsonl files in a directory. And you can easily go through each file in the directory by using the glob.glob module.

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.

About

Pro Golang is a site to read about tutorials, tips and tricks and other articles about the Go programming language.