How to build and test a REST API in Golang with PostgreSQL


This tutorial illustrates how you can build a REST API backed by PostgreSQL in Golang, using Gorilla Mux for routing. The tutorial will employ test-driven development and will explain how you can continuously test against a database during development.

Golang Tutorial Goals

By the end of this tutorial, you will:

  • Become familiar with Gorilla Mux, and
  • Learn how to test your application against a Continuous Integration (CI) database.

Prerequisites

This tutorial assumes:

  • Basic familiarity with Go and PostgreSQL, and
  • That you have to work Golang and PostgreSQL installations.
  • You can use Docker to run a test database easily.

You’ll find the complete code for the demo at this repository.

TomFern/go-mux-api

Introduction to the Golang Application

Before we dive into the details, let’s take a brief look at the sample application we will be building as part of this tutorial.

What Will the Go Application Do?

The application will be a simple REST API server that will expose endpoints to allow accessing and manipulating ‘products’. The operations that our endpoint will allow include:

  • Creating a new product,
  • Updating an existing product,
  • Deleting an existing product,
  • Fetching an existing product, and
  • Fetching a list of products.

RESTful API Specification