This project is a simple REST API built using the Gin framework in Go. It provides endpoints to manage products in a database, including operations for listing, retrieving, creating, updating, and deleting products.
- CRUD Operations: Create, Read, Update, and Delete products 📝
- MySQL Database Integration: Uses GORM to connect and interact with a MySQL database 🗄️
- JSON-based API: Responses are provided in JSON format 📦
- Auto-migration: Automatically creates and updates the product table 🔄
- Go version 1.23.1 or higher 🚀
- MySQL Database 🗄️
- (Optional) Docker for running MySQL locally 🐳
-
Clone the repository:
git clone https://github.com/thoriqdharmawan/go-rest-api-gin.git cd go-rest-api-gin
-
Install the required Go modules:
go mod tidy
-
Set up MySQL and create a database:
CREATE DATABASE go_restapi_gin;
-
Update the MySQL connection string in
models/database.go
:"root:root@tcp(localhost:3306)/go_restapi_gin"
Replace
root:root
with your MySQL username and password.
-
Start the application:
go run main.go
-
The API will be available at
http://localhost:8080
🌐.
- Endpoint:
GET /api/products
- Description: Retrieve all products from the database.
- Response:
[ { "id": 1, "nama_product": "Product 1", "deskripsi": "Description of Product 1" }, ... ]
- Endpoint:
GET /api/products/:id
- Description: Retrieve a specific product by its ID.
- Response:
{ "id": 1, "nama_product": "Product 1", "deskripsi": "Description of Product 1" }
- Endpoint:
POST /api/products
- Description: Create a new product.
- Request Body:
{ "nama_product": "New Product", "deskripsi": "New Product Description" }
- Response:
{ "id": 2, "nama_product": "New Product", "deskripsi": "New Product Description" }
- Endpoint:
PUT /api/products/:id
- Description: Update an existing product by its ID.
- Request Body:
{ "nama_product": "Updated Product", "deskripsi": "Updated Description" }
- Response:
{ "id": 1, "nama_product": "Updated Product", "deskripsi": "Updated Description" }
- Endpoint:
DELETE /api/products
- Description: Delete a product from the database.
- Response:
{ "message": "Product deleted successfully" }
The product model used in this project:
type Product struct {
Id int64 `gorm:"primaryKey" json:"id"`
NamaProduct string `gorm:"type:varchar(300)" json:"nama_product"`
Deskripsi string `gorm:"type:text" json:"deskripsi"`
}
This project uses the following Go packages:
- Gin v1.10.0: HTTP web framework.
- GORM v1.25.12: ORM for Go.
- Go MySQL Driver v1.7.0: MySQL driver for Go.