recipes/local-development-testcontainers

Todo App + Auth + GORM + Testcontainers

A Todo application with authentication using GORM and Postgres.

Todo App with Auth using GORM and Testcontainers

Github StackBlitz

This project demonstrates a Todo application with authentication using GORM and Testcontainers.

The database is a Postgres instance created using the GoFiber's Testcontainers Service module. The instance is reused across multiple runs of the application, allowing to develop locally without having to wait for the database to be ready.

When using the air command to run the application, the database is automatically started alongside the Fiber application, and it's automatically stopped when the air command is interrupted.

Prerequisites

Ensure you have the following installed and available in your GOPATH:

  • Golang
  • Docker, which Testcontainers uses to start the PostgreSQL container
  • Air for hot reloading
  • Godotenv CLI, which .air.conf uses to load .env

Installation

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/local-development-testcontainers
  2. Install dependencies:

    go get
  3. Create the environment file and add a secret for signing the JWTs. air loads .env, and the application refuses to start without TOKEN_KEY:

    cp .env.example .env
    echo "TOKEN_KEY=$(openssl rand -hex 32)" >> .env

Running the Application

  1. Start the application:
    air

Environment Variables

VariableDescriptionDefault
PORTServer listening port8000
DBPostgreSQL connection string. Only builds without the dev tag use it. air builds with -tags dev, which starts a PostgreSQL container with Testcontainers and ignores DBpostgres://postgres:postgres@localhost:5432/postgres?sslmode=disable
TOKEN_KEYSecret used to sign the JWTs. Generate a random one with openssl rand -hex 32required
TOKEN_EXPToken lifetime, a time.ParseDuration string10h
TESTCONTAINERS_RYUK_DISABLEDDisables the Ryuk container so the database container is not removed when the application stopstrue in .env.example