Skip to content

Compiling The Code

Even though our code is simple, I still wanted to cover the compilation process so that you can compile and execute it locally.

The source, if you haven't worked it out by now, is written in Golang. You're going to need to install Go before you're able to compile the code. Follow the official instructions for installing go on your platform. It could change, and there's a lot of variation in this process, so I won't cover installing the compiler here.

Once Go is installed, we can start compiling our code.

Running

Before we can compile you're going to have to ensure you have a few things in your httpcats repository:

  1. You've written the source code out into main.tf
  2. You've got the static content in place, including the images of the cats

Once those things are sorted, we need to create a Go module:

1
go mod init httpcats

This will generate a go.mod file.

Next we should be able to simply run the application:

1
go run .

This will compile the application (in the background) and execute the result. It'll look a bit like this:

1
2
$ go run .
2021/06/18 13:30:14 Listening on 0.0.0.0:8080

Now the service is listening on port 8080.

Address Already In Use

If you get the following error, then you have the application running already or something else is using port 8080:

1
2
3
4
$ go run .
2021/06/18 13:31:26 Listening on 0.0.0.0:8080
2021/06/18 13:31:26 listen tcp 0.0.0.0:8080: bind: address already in use
exit status 1

Compiling to a Binary

Running the application locally is one thing, but to deploy it we need to compile it. Our GitLab CI Runner will do this for us, but we'll also compile it locally so we know what the CI process is doing for us.

Compiling is a bit more involved:

1
go build -v -o "httpcats"

Now an important lesson to learn here is this: the binary you get from this, called httpcats, will be compiled for your local system's architecture. That means if you're on Windows you'll get an EXE. If you're on macOS you'll get a different executable again. This isn't an issue, it's just something to be aware of, and it means you cannot compile once on your system and have the result work on all systems. Instead you have to compile for each platform you want to target.

All that being said, once you have compiled the application to a binary called httpcats, you can now just run it:

1
2
$ ./httpcats
2021/06/18 13:30:14 Listening on 0.0.0.0:8080

Last update: August 25, 2021