DEV Community

Hamed Naeemaei
Hamed Naeemaei

Posted on • Updated on

Golang Web API Course: Project structure

Before entering the code environment, in this section, we will get to know the project's structure.
One of the points that must be observed in project architecture is the principle of separation of responsibilities. In this project, we have considered a specific responsibility for each layer, and the layers operate independently. For example, you can use another framework instead of the gin framework or not use the framework.

Golang web API project structure

In general, the project consists of several main parts:

1. API

This layer is the only part of the project where the gin framework is used, and this layer only manages concepts related to web API such as routing, validation, middleware, etc.

API layer in golang

1.1 API.go file

Registration of middlewares, routes, validators, and all web server configurations is handled in this file. Functions of this file are called from main.go

1.2 DTO

All DT objects that transfer data between the API layer and the business layer are defined in this directory.

1.3 Routers

The starting point of receiving the request is in the router package. this package checks route sections and HTTP verbs then sends requests to handlers.

1.4 Handlers

This package gets requests from the router package and sends them to the service layer. swagger configs set in this package

1.5 Middlewares

All middlewares including authentication, authorization, CORS, rate limiters, Prometheus, request logger and etc are defined here

2. SERVICES

Business logic and services are written in this layer. this package was called by handlers and called the data layer to work with the database.

service layer in golang

3. DATA

In this layer, all the work of connecting with the database(postgres and redis) and working with data is done. This package is called from the service layer.

data layer in golang

Other sections

4. CMD(main.go)

This is the starting point of service execution in this section. The main.go file after initializing cache, database, and logger, call api.go file.

golang web API with gin main.go file

5. COMMON

Useful and widely used functions are defined in this layer.

6. CONFIG

Project configurations and their management are located in this section.

golang web API with gin config files

7. CONSTANTS

Project constants are defined here.

8. DOCS

Swagger information and settings are located in this section.

9. PKG

External packages are located in this section.

limiter, logging, metrics and service errors in golang project

10. TEST

Project tests are written in this section.

11. Docker

In this section, there is a Docker compose file of the main project, Prometheus, Grafana, Elasticsearch, Kibana, filebeat, Postgres, and Redis. To run the project, it is enough to up the Docker Compose file.

dockerize golang project

Top comments (0)