This is a sample Go REST API project that demonstrates how to perform CRUD operations on a Product resource using the Gin framework and PostgreSQL. The project also includes middleware for logging the IP address of incoming requests.
go-rest-api
│ main.go
├───config
│ config.go
├───controllers
│ product_controller.go
├───middleware
│ ip_logger.go
├───models
│ product.go
│ database.go
├───routes
│ routes.go
└───utils
response.go
- Create, read, update, and delete products
- Log IP addresses of incoming requests
- Go 1.20 or higher
- PostgreSQL
- Git
- Docker (optional, for running PostgreSQL in a container)
-
Clone the repository:
git clone https://github.com/hasithaishere/go-rest-api-with-postgresql.git cd go-rest-api -
Install dependencies:
go mod tidy
-
Set up PostgreSQL:
-
Option 1: Using Docker (Recommended)
-
Run PostgreSQL in a Docker container:
docker run --name postgres-db -e POSTGRES_USER=your_db_user -e POSTGRES_PASSWORD=your_db_password -e POSTGRES_DB=your_db_name -p 5432:5432 -d postgres
-
Update the
.envfile with your PostgreSQL credentials:DB_USER=your_db_user DB_PASSWORD=your_db_password DB_NAME=your_db_name DB_HOST=localhost DB_PORT=5432
-
-
Option 2: Local PostgreSQL Installation
-
Create a new PostgreSQL database.
-
Update the
.envfile with your PostgreSQL credentials:DB_USER=your_db_user DB_PASSWORD=your_db_password DB_NAME=your_db_name DB_HOST=your_db_host DB_PORT=your_db_port
-
-
-
Create the
productstable in your PostgreSQL database:CREATE TABLE products ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, price INTEGER NOT NULL, created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP );
-
Start the application:
go run main.go
-
The server will start on
http://localhost:8080.
- GET /products: Retrieve all products
- POST /products: Create a new product
- Request body:
{ "name": "Sample Product", "price": 100 }
- Request body:
- GET /products/:id: Retrieve a product by ID
- PUT /products/:id: Update a product by ID
- Request body:
{ "name": "Updated Product", "price": 150 }
- Request body:
- DELETE /products/:id: Delete a product by ID
-
Create a product:
curl -X POST http://localhost:8080/products \ -H "Content-Type: application/json" \ -d '{ "name": "Sample Product", "price": 100 }' -
Get all products:
curl http://localhost:8080/products
-
Get a product by ID:
curl http://localhost:8080/products/1
-
Update a product by ID:
curl -X PUT http://localhost:8080/products/1 \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Product", "price": 150 }' -
Delete a product by ID:
curl -X DELETE http://localhost:8080/products/1
The project includes a middleware that logs the IP address of incoming requests. The middleware is defined in middleware/ip_logger.go and is registered in the router setup in routes/routes.go.
This project is licensed under the MIT License. See the LICENSE file for details.