Build and Test an API with Golang and MongoDB (Authentication with JWT, Dependency Mocking, & Data Validation)

A primer on API development with Golang

source

Introduction

Prerequisites

What you will learn

First steps

go mod init projectName
go get github.com/labstack/echo/v4

Code organization

internal/api/api.go
internal/api/health.go
go run cmd/api/main.go

Our first make command

go run cmd/api/main.go
makefile
make run

External configuration

.env
pkg/config/config.go

Connecting to mongo

go get go.mongodb.org/mongo-driver
docker-compose.yml
docker-compose up -d
Docker Desktop
pkg/data/connection.go
cmd/api/main.go
make run
makefile

Designing models

pkg/domain/users.go

Errors

pkg/models/errors.go

Requests

Responses

pkg/models/responses.go

The data layer

The user service

pkg/services/user.go

📔 What’s going on:

Registering our handlers

internal/api/users.go

📔 What’s going on:

internal/api/api.go

Authentication middleware

internal/api/middleware.go

📔 What’s going on:

internal/api/api.go

📔 What’s going on:

Testing

go get github.com/stretchr/testify
pkg/mocks/data/users/mocks.go

📔 What’s going on:

pkg/services/user_test.go

📔 What’s going on:

go test ./...
pkg/mocks/data/users/integration.go

📔 What’s going on:

internal/api/users_test.go

📔 What’s going on:

Wrap up

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store