Developing a RESTful API with Go, Gin and GORM — Part 1 (Router Setup + DB Configuration)

Venu Prasanna M
4 min readJun 13, 2022

--

What is a RESTful API ?

REST API stands for representational state transfer and it’s an architectural style for an application program interface that uses HTTP request to access and use data. That data can be used for reading, updating, creating and deleting concerning resources.

What is GORM?

GORM is a ORM library written in go lang which provides CRUD operations and can also be used for the initial migration and creation of database schema.

What is GIN?

Gin is a high-performance HTTP web framework written in Golang.

Note: This article will be split into multiple sub articles. This article is the first part.

Initialization

Lets Initialize our project

  • Install go lang
  • Create project pages
> mkdir pages
> cd pages
> go mod init example/venu/pages

Project Structure

(project file structure)

Main.go

First let’s start from main.go, this file will be our entry point so let’s add the main function here. Since this is our main function we name it main and also the package name should be main. The main function will pull the configuration details from the config.yaml file and initialize the router.

In ./main.go

Configuration Setup

As the main function is ready now let’s do the configuration setup.

Add Config struct — this struct will be the root one which will hold all kinds of configurations. Let’s add database configuration.

Add DatabaseConfig struct to config.go file which will hold all the necessary details to connect to the database.

Add NewConfig function which will read config.yaml and return *Config which will be provided to the InitRouter method later.

In ./setup/config.go

Add database details in config.yaml

In ./setup/config.yaml

Add docker-compose.yaml and we need to add a db service which runs postgres on port 5432.

In ./setup/docker-compose.dependency.yml

Router Initialization

In this project we are going to use the Gin framework, which is a high performance HTTP web framework.

First of all Install gin framework

$ go get -u github.com/gin-gonic/gin

Now let’s set up the init router method. Navigate to ./router/root.go

Add function InitRouter which will receive config as parameter and return *gin.Engine.

In this method we will define the gin default router and map them to their handlers later. Let’s return the default router.

Database

Navigate to ./db/database.go

In this folder we will add methods to set up a new database connection.

First let’s write a method that will prepare the DNS.

Now let’s write the function that would open a postgres connection.Before doing that we need to install GORM and postgres driver.

Install gorm

$ go get -u github.com/gin-gonic/gin

Install postgres driver

$ go get -u gorm.io/driver/postgres

In ./db/database.go

Health Check Endpoint

Now let’s write a handler for the health endpoint. Create a folder health under ./pages/api/

Let’s start with the unit test, where we test that the health check endpoint would return a JSON response with HTTP status code 200.

Install go stretcher/testify

go get github.com/stretchr/testify

In ./pages/api/health/handler_test.go

In the test method first we declare the expected response.

We need a httptest recorder to record the http response. It also needs context to initialize the handler. Then we make a new GET request using httptest.NewRequest. After that we decode the response as Response struct and check for expected status code as 200 and the response message.

Now let’s define our health check handler. Create a function HealthCheck which will take gin.Context as a parameter. We also need a struct for holding the response with a message field in it.

In ./pages/api/health/handler.go

Now let’s run the test and it should fail as the response doesn’t match. By default the handler will return HTTP status 200 Ok.

cmd to run test in terminal

go test ./api/health/Error Trace: handler_test.go:28Error: Not equal:expected: health.Response{Message:”Alive”}actual : health.Response{Message:””}Diff: — — Expected+++ Actual@@ -1,3 +1,3 @@(health.Response) {- Message: (string) (len=5) “Alive”+ Message: (string) “”}Test: TestHealthCheck_ShouldReturnSuccess

Now let’s update the health check handler and pass the test.

After this the test should pass.

Now update ./router/root.go for health endpoint.

Now let’s try running the application.

First we have to run the postgres container for the database in the terminal.

docker-compose -f ./setup/docker-compose.dependency.yml up -d

After that run main.go

go run ./main.go

Try hitting http://localhost:8080/health in the browser

Hurray! We have successfully done the basic setup and added our first handler.

Coming up next

  • Table driven tests (TDD)
  • Setting up Repository and Repository test cases
  • Pagination using GIN + GORM

--

--