Membangun API CRUD dengan Go, Gin, MySQL, dan GORM
Di tulisan ini, saya akan membuat API CRUD (Create, Read, Update, Delete) sederhana menggunakan Go dengan framework Gin, MySQL sebagai basis data, dan GORM sebagai ORM (Object Relational Mapping). Untuk mengelola konfigurasi seperti kredensial database, saya juga akan memakai paket godotenv
.
1. Menyiapkan Proyek
Pertama, buat direktori baru untuk proyek lalu inisialisasi modul Go:
mkdir myapp
cd myapp
go mod init myapp
2. Menginstal Dependensi
kita butuh beberapa paket:
- Gin untuk menangani HTTP request
- GORM untuk ORM
- MySQL driver untuk koneksi database
- godotenv untuk membaca file
.env
Jalankan:
go get -u github.com/gin-gonic/gin
go get -u gorm.io/gorm
go get -u gorm.io/driver/mysql
go get -u github.com/joho/godotenv
3. Membuat Database MySQL
Masuk ke MySQL dan buat database baru:
CREATE DATABASE myapp;
4. Menyiapkan Variabel Lingkungan
Buat file bernama .env
di root proyek, lalu isi dengan detail koneksi database:
DB_USER=root
DB_PASSWORD=yourpassword
DB_NAME=myapp
DB_HOST=127.0.0.1
DB_PORT=3306
⚠️ Jangan lupa tambahkan file
.env
ke.gitignore
supaya kredensial database tidak ikut ter-commit ke repository.
5. Menulis Kode Aplikasi
Buat file app.go
dan tambahkan kode berikut:
package main
import (
"log"
"os"
"net/http"
"github.com/gin-gonic/gin"
"github.com/joho/godotenv"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
var DB *gorm.DB
type Book struct {
gorm.Model
Title string `json:"title"`
Author string `json:"author"`
Price float64 `json:"price"`
}
func init() {
// Load konfigurasi dari .env
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Buat DSN untuk koneksi database
dsn := os.Getenv("DB_USER") + ":" + os.Getenv("DB_PASSWORD") + "@tcp(" +
os.Getenv("DB_HOST") + ":" + os.Getenv("DB_PORT") + ")/" +
os.Getenv("DB_NAME") + "?charset=utf8mb4&parseTime=True&loc=Local"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal("Failed to connect to database:", err)
}
// Auto migrate model Book
db.AutoMigrate(&Book{})
DB = db
}
func main() {
r := gin.Default()
r.POST("/books", CreateBook)
r.GET("/books", GetBooks)
r.GET("/books/:id", GetBook)
r.PUT("/books/:id", UpdateBook)
r.DELETE("/books/:id", DeleteBook)
r.Run(":8080")
}
func CreateBook(c *gin.Context) {
var book Book
if err := c.ShouldBindJSON(&book); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
DB.Create(&book)
c.JSON(http.StatusOK, book)
}
func GetBooks(c *gin.Context) {
var books []Book
DB.Find(&books)
c.JSON(http.StatusOK, books)
}
func GetBook(c *gin.Context) {
id := c.Param("id")
var book Book
if err := DB.First(&book, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Book not found"})
return
}
c.JSON(http.StatusOK, book)
}
func UpdateBook(c *gin.Context) {
id := c.Param("id")
var book Book
if err := DB.First(&book, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Book not found"})
return
}
if err := c.ShouldBindJSON(&book); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
DB.Save(&book)
c.JSON(http.StatusOK, book)
}
func DeleteBook(c *gin.Context) {
id := c.Param("id")
var book Book
if err := DB.First(&book, id).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Book not found"})
return
}
DB.Delete(&book)
c.JSON(http.StatusOK, gin.H{"message": "Book deleted"})
}
6. Menjalankan Aplikasi
Jalankan aplikasi dengan:
go run app.go
Server akan aktif di http://localhost:8080
.
7. Menguji Endpoint API
Gunakan curl
atau Postman untuk mencoba API.
1. Membuat Buku
curl -X POST http://localhost:8080/books \
-H "Content-Type: application/json" \
-d '{"title": "Go Programming", "author": "John Doe", "price": 29.99}'
2. Mendapatkan Semua Buku
curl http://localhost:8080/books
3. Mendapatkan Buku Berdasarkan ID
curl http://localhost:8080/books/1
4. Memperbarui Buku
curl -X PUT http://localhost:8080/books/1 \
-H "Content-Type: application/json" \
-d '{"title": "Advanced Go", "author": "Jane Doe", "price": 39.99}'
5. Menghapus Buku
curl -X DELETE http://localhost:8080/books/1
Kesimpulan
Dengan Go, Gin, MySQL, dan GORM, kita bisa membangun API CRUD dengan cepat sekaligus menjaga struktur kode tetap bersih.
Menggunakan file .env
membantu memisahkan konfigurasi dari kode, sehingga aplikasi lebih mudah dipelihara dan lebih aman.
Dari sini, kamu bisa mengembangkan fitur tambahan seperti autentikasi, pagination, hingga middleware khusus sesuai kebutuhan aplikasi.