Go 1.11 Rocket Tutorial


This tutorial combines two of my favorite things, the Go programming language and images of SpaceX rocket launches.

With Go rapidly picking up adoption in the developer community, its becoming one of the leading languages for building backend systems. Go’s performance is similar to Java and C++, yet it’s almost as easy to write as Python. Since its inception in 2009 by Google, Go has been adopted by Netflix, Stripe, Twitch, Digital Ocean and many others. Here at Stream we use Go & RocksDB to power news feeds for over 300 million end users.

In this tutorial, you’ll build a highly concurrent web server which reads SpaceX images from the  Unsplash API and applies seam carving on those images. The pace is high and assumes you already know how to program. You’ll learn the basics of Go and we’ll also cover more advanced topics such as Goroutines and Channels.

Part 1 - Setup and Seam Carving

Step 1 - Install Go 1.11

Homebrew on macOS is the easiest way to install Go:

Loading code sample...

Alternatively head over to the official Go download page and follow the install instructions for your system.

Be sure that you have installed Go 1.11 or later before continuing this guide. Once installed, check your version with

Loading code sample...

Step 2 - A Simple Request Handler

Go v1.11 simplified the initial setup of a Go project. Older versions of Go required the GOPATH environment variable. With v1.11 you can follow the three steps below to get your server up and running:

A. Create a directory

Create an empty directory called rockets:

Loading code sample...

B. Go mod init

Run the following command to start a new Go module:

Loading code sample...

This will create a file called go.mod in your directory. This file will contain your dependencies. It is similar to package.json in Node, or requirements.txt in Python. (Go doesn’t have a package repository

C. main.go

Create a file called main.go in the rockets directory with the following content. (The full path is rockets/main.go):

Loading code sample...

You can run it like this:

Loading code sample...

After a moment of installing dependencies, you’ll be able to visit http://localhost:3000/occupymars

Click the “Resize using Seam Carving” link to start the resizing. The computation is quite heavy and may take a bit, so give it a few seconds.

Voila, one resized rocket picture:

Step 3 - Go’s Syntax

The first thing you’ll notice in the above example is that Go is very similar to other programming languages. Let’s quickly review the code in main.go:

A. Go is a statically typed language

Loading code sample...

The function takes a string as input and returns a slice of bytes and an error.

B. Go infers types

Loading code sample...

Is short for:

Loading code sample...

Here’s the syntax for the most commonly used types in Go:

Loading code sample...

LearnXinY is a great resource to quickly check the Go syntax.

C. Types are also inferred when calling functions

Loading code sample...

Note how the function returns two elements which we use to initialize these new variables:  resized and err.

D. Go & Unused variables

One of the quirks of Go is that unlike most other languages it will throw a syntax error if you leave a variable or import unused. If you add the following code after the shrinkFactor on line 29:

Loading code sample...

And run main.go you’ll get the following error:
./main.go:30:12: oldvariable declared and not used
Most editors will help you clean up unused code, so in practice this is not that annoying. If you want to ignore one of the variables returned by a function you can do it like this:

Loading code sample...

The _ simply means discard the value.

E. Interfaces

On line 36 the p.Process function converts the image in response.Body and stores it in the converted variable. What’s interesting is the function definition of p.Process:

Loading code sample...

This function takes an io.Reader as the first argument and an io.Writer as the second. io.Reader and io.Writer are interfaces. Any type that implements the methods required by these interfaces can be passed to the function.

Note: One interesting fact about interfaces in Go is that types implement them implicitly. There is no explicit declaration of intent, no "implements" keyword. A type implements an interface by applying its methods.

(Fun read: This blogpost about Streaming IO in Go gives more details about the io.Reader and io.Writer interfaces)

F. Imports

Loading code sample...

The import syntax is easy to understand. Let’s refactor the ContentAwareResize function into a separate package to clean up our code.

Step 4 - Refactoring to a Package

A. Create a directory with the name “seam”:

Loading code sample...

Your full path will look like rockets/seam.
Note: If you’re wondering why the folder is called seam it’s because this type of content aware image resizing is also typically called seam carving.

B. In the seam directory, create a file called “seam.go” with the following content:

Loading code sample...

C. Open main.go and make the following changes:

  1. Remove the import for "github.com/esimov/caire"
  2. Remove the import for "github.com/pkg/errors"
  3. Add the import for "github.com/GetStream/rockets-go-tutorial/seam"
  4. Update the function call in main.go from ContentAwareResize to seam.ContentAwareResize (Line 50)
  5. Remove the ContentAwareResize function from main.go (Line 18-43) 

To clarify, before the changes the function call looked like this:

Loading code sample...

After the changes you’re calling the method defined in the seam module like this:

Loading code sample...

D. See if it worked:

Start the server and see if it still works!

Loading code sample...

If everything went according to plan you should still be able to access at http://localhost:3000/occupymars
Note: Packages give you a nice way to structure your code. Capitalized functions are public and lowerCase functions are private.
If something went wrong with these steps you can also clone the Github repo for a working version:

Part 2 - Unsplash API, Channels and Concurrency


Step 5 - APIs, Structs and JSON

You’re already well on your way to learning Go. Easy right? Not bad for a language that’s 20-40 times faster than Python!
For this second example we’ll learn how to use read data from an API. We’ll use the excellent Unsplash photography API to search for more rocket pictures.

A. Create a folder called unsplash:

Loading code sample...

The full path is rockets/unsplash.

B. Inside the unsplash directory create a file called unsplash.go with the following content:

Loading code sample...

C. Update rockets/main.go to match this content:


D. Create a file called rockets/spacex.html:

The content should match this:

Loading code sample...

E. Restart your Go server:

Loading code sample...

Assuming nothing went wrong you can now open up this URL
You should see the latest images tagged with SpaceX on Unsplash:


Step 6 - Understand Those API Calls

Let’s open up unsplash.go and have a look at how the code works:

A. Making the request:

Go’s builtin HTTP library is pretty functional, here’s the GET request to the Unsplash API

Loading code sample...

B. Structs and methods:

Go has objects but it’s different from traditional object oriented languages because it doesn’t support inheritance. Go relies on composition instead of inheritance to help you structure your code. Structs in Go are the closest you’ll come to classes in more object oriented languages. Let’s see how we’re using Structs to talk to the Unsplash API in unsplash.go:

Loading code sample...

The NewAPIClient creates a new APIClient struct. The Search method enables you to write code like:

Loading code sample...

This blogpost explains the concept of composition nicely.

C. Parsing JSON:

Since Go is a statically typed language you’ll want to parse the JSON into a Struct. If you’re coming from a dynamic language this will be a little bit confusing at first. You’ll get the hang of it quickly. The Unsplash API returns the following JSON:

Loading code sample...

There are more fields in the JSON but I simplified it a bit for the example. Next we’ll want to parse the JSON into the following structs:

Loading code sample...

The struct definition specifies the mapping between the field name in the JSON and the struct:

Loading code sample...

This means that when decoding JSON it will take the value from the total_page and set it to the TotalPages property.
To decode the JSON we use the following code:

Loading code sample...

We create a new APIResponse struct and parse a pointer to this object in the Decode function.
The next section will discuss pointers in more detail.

D. The defer statement

One of the fairly unique concepts of Go is the defer statement. In unsplash.go line 41 you see the following defer statement:

Loading code sample...

Deferred function calls are pushed onto a stack. When a function returns, its deferred calls are executed in last-in-first-out order. So after the Search function finishes the defer statement will trigger and close the request body.

Step 7 - Pointers

Throughout this tutorial you probably spotted the and & symbols. These two are used in Go to work with pointer variables. You can think of pointer variables as references to values. Every type in Go can have its pointer counterpart; you can easily tell if a variable is a pointer or not since its type will start with the symbol.

Loading code sample...

The & and also work as operators: & returns a pointer to its value and returns the value a pointer refers to.

A. Basic Pointer operations:

If you haven’t used pointers before this concept can be a little bit confusing at first. This little snippet clarifies how pointer operations work:

Loading code sample...

You can run the above example in the Go Playground

B. Pointers & Functions:

The example below shows how functions can accept both pointers and regular types:

Loading code sample...

You can run the above example in the Go Playground
If you’re new to the concept of Pointers you might also enjoy the “Understand Go pointers in less than 800 words” blog post.

C. Pointer Method Receivers:

One thing that trips up a lot of new Go developers is the way you attach methods to structs:

Loading code sample...

In this example we’re attaching the Search function to the *APIClient type. This allows us to invoke it using this syntax:

Loading code sample...

So far so good. However if you use APIClient instead of *APIClient you’ll run into two unintended consequences:

  • Go will create a copy of your struct while calling the function. Changes you make will only affect your copy
  • Memory usage goes up because you’re copying your struct

Note that this isn’t always a bad thing. In some cases it’s actually faster to not use pointers. Here’s an example of where it goes wrong though:

Loading code sample...

You can run it on the Go playground to see why the above code doesn’t work:
TL/DR use pointer receivers unless you have a good reason not to. The “Don't Get Bitten by Pointer vs Non-Pointer Method Receivers in Golang” covers this issue in more detail.

Step 8 - Errors

Errors in Go are just variables that you return. Conceptually this approach is very easy to reason about when working with concurrent programming. It can be a bit hard to get the right workflow though. So before you get to read about channels & concurrency (the next topic) we’ll bore you with some mandatory error handling best practices:

A. Errors are returned as the last argument of a function:

Don’t deviate from this standard, if you’re writing a function that can fail be sure to allow for an error object as the last return value.

Loading code sample...

B. Stack traces & Errors.Wrap:

The default errors don’t include a stack trace. This is why pretty much every Go app uses the pkg/errors module to wrap errors.

Loading code sample...

C. Error causes:

The pkg/errors module also makes it easy to detect the cause of the error.

Loading code sample...

D. Let errors bubble up:

Most of the time you want to centralize your error handling in one place of your app. You’ll for instance want to return a 500 from your server and log the error in Sentry.
That’s why most functions at the lower levels just return an error in case something breaks. You’ll see this pattern often:

Loading code sample...

Step 9 - Channels & Goroutines

Channels are probably one of the sexiest features of Go. In this part of the tutorial we’ll take a deep dive on how you can leverage Goroutines and Channels for asynchronous programming in Go.
It's good to remember that channels are a feature for power users. By default Go uses a separate Goroutine for every incoming request. So typically you already get the benefit of a highly concurrent server without ever thinking about asynchronous programming. As the creator of Node said: “I think Node is not the best system to build a massive server web. I would use Go for that...
Channels and Goroutines give you powerful tools to implement concurrency. For this exercise we’ll start 4 worker goroutines to download and resize 8 pictures from the Unsplash API.
Head over to http://localhost:3000/spacex_seams and watch the log output. You’ll see that 4 workers are downloading and resizing the images concurrently. Depending on the speed of the machine this will take anywhere from 1-20 seconds.

Let’s have a look at main.go to see how this works.

A. Channel Creation:

As a first step we create a channel for tasks and a channel for results:

Loading code sample...

B. Starting the workers:

This loop starts the workers

Loading code sample...

The “go” statement run the specified function in a separate Goroutine. A Goroutine is a very lightweight alternative to threads. Since a Goroutine only takes 2kb of overhead you can run millions of them even on commodity hardware.
The Goroutines execute the following code:

Loading code sample...

Note how the worker uses the range keyword to iterate over the taskChannel till it’s closed. When the worker receives a new task on the taskChannel it downloads the image, resizes it and writes the result to the resultChannel.

C. Write to the task channel:

As a next step we write to the taskChannel and close the channel when we’re done.

Loading code sample...

Writing or reading from a channel is a blocking operation. To prevent a situation in which we’re waiting forever we run this code in a separate Goroutine. Note the go func() {…}() syntax to execute the code in a Goroutine.

D. Retrieving the results:

This loop retrieves the results from the resultChannel and base64 encodes it for easy embedding in the resulting page.

Loading code sample...

Channels & Goroutines

And that’s it. Channels are a pretty low level concept. Go also provides Mutexes and Wait groups to help with concurrent programming. When your first learn about Channels it’s easy to become excited and use them to solve every problem. Some issues like preventing multiple writes on a shared object are sometimes easier solved using a simple Mutex. This wiki provides some guidelines on when to use a sync.Mutex or a Channel.
The cool part about Go’s concurrency model is that most of the time you don’t even need to think about it. You just write your synchronous code and Go handles the switching between Goroutines without you, the programmer, doing any work.
Channels, GoRoutines, Wait Groups and Mutexes give you full control over how you’re writing asynchronous code when you need it. If you want to learn more about channels check out this Golang channels tutorial.

Step 10 - Libraries and Tools

Go is an easy language to learn. What tends to take more time is figuring out the tooling and the ecosystem. Here are a few library and tool recommendations to help you get started.
Tool: Go doc
Go doc is an awesome little tool for generating reference docs for your Go APIs.
Tool: go fmt & go imports
Go fmt and go imports two tools help you automatically clean up your Go files.
Go ships with awesome profiling capabilities and beautiful flamegraphs about your code’s performance. This tutorial is a solid starting point: https://jvns.ca/blog/2017/09/24/profiling-go-with-pprof/

Mux is an awesome little library for URL routing in Go:
The aptly named CLI is a great library for building command line interfaces in Go.
Zap, Uber’s logging library, is a better alternative to Logrus and the default Go logging system.
Go Rice enables you to easily embed static files such as templates into your Go binary.
Squirrel makes it easy to work with SQL in Go.
One of the reasons why we picked Go is the mature ecosystem of libraries. Most of the time you’ll find high quality open source libraries to help you with your projects.

Concluding the Go Tutorial

At Stream we use Go & RocksDB to power the news feeds for over 300 million end users. What’s unique about Go is the balance it strikes. It’s ridiculously fast and still easy and productive to work with.

It’s been 18 months since Stream switched from Python to Go. There is always some uncertainty when making such a large change. Fortunately moving to Go worked out very well. We’re able to power a complex and large infrastructure with a relatively small development team. Go improves with every release. Every time a new version is released we rerun our benchmarks shave a few milliseconds of our response times. The tooling also gets better with every release.

Go is a fun language and I hope you enjoyed this tutorial. We covered the basics and even some more advanced topics such as Goroutines and Channels. Let me know if anything in this tutorial isn’t clear (@tschellenbach).

If you’ve never used Stream before, try out this Tour of the API. You can try it out with Javascript in the browser, or of course with the official Stream Go client.