This is a Golang project template or boilerplate code designed to kickstart the development of RESTful APIs using the Gin framework. The template includes basic endpoints for adding and retrieving user information, integrates the Zap logger for efficient logging, utilizes middleware to log incoming requests, and leverages Swagger for API documentation. The project is configured to use PostgreSQL as the database, and all configurations are customizable through environment variables.
Before getting started with the project, ensure that the following prerequisites are met:
-
Install the pre-commit package manager:
sudo snap install pre-commit --classic
-
Install git hook scripts:
pre-commit install
-
Install golangci-linter:
go install github.com/golangci/golangci-lint/cmd/[email protected]
-
Install Swag Tool for API documentation:
go get -u github.com/swaggo/swag/cmd/[email protected]
Make sure to set the following environment variables according to your requirements:
SERVER_PORT
: Port on which the server will run (default: 8000).BUILD_ENV
: Build environment (default: dev).
For database configuration:
DB_HOST
: PostgreSQL database host (default: localhost).DB_PORT
: PostgreSQL database port (default: 5432).DB_USERNAME
: PostgreSQL database username (default: postgres).DB_PASSWORD
: PostgreSQL database password (default: 1234).DB_NAME
: PostgreSQL database name (default: gin_service).
The project structure follows the updated layout to improve organization and separation of concerns:
controllers/
: HTTP request handlers.docs/
: Documentation files.env/
: Environment variable management.handlers/
: Logic for processing HTTP requests.logger/
: Logging configuration and setup.middlewares/
: Custom middleware functions.models/
: Data structures and database models.services/
: Database interactions logic.utils/
: Utility functions.
-
Clone the repository:
git clone https://github.com/yourusername/gogintemplate.git cd gogintemplate
-
Update Swagger documentation:
swag init
-
Run the application:
go run main.go
-
Access Swagger Documentation:
Open your browser and navigate to:
http://<SERVER_HOST>:<SERVER_PORT>/gin-service/api/v1/swagger/index.html
A Dockerfile is provided to enable easy containerization of the application. Build and run the Docker container as follows:
docker build -t gogintemplate .
docker run -p <HOST_PORT>:<SERVER_PORT> gogintemplate