Proyek: Aplikasi Go dan PostgreSQL
REST API katalog item yang ditulis dengan Go standar (net/http) dan PostgreSQL
lewat driver jackc/pgx/v5. Aplikasi menjalankan migrasi skema secara otomatis
saat startup, siap menerima SIGTERM dengan graceful shutdown, dan diuji lewat
integration test black-box yang berjalan sebagai service Compose terpisah.
Struktur Berkas #
| Berkas | Peran |
|---|---|
main.go | Konfigurasi environment, routing, graceful shutdown |
database.go | Koneksi dengan retry dan runner migrasi schema_migrations |
handlers.go | Handler HTTP untuk seluruh endpoint |
go.mod / go.sum | Definisi dan checksum dependensi |
migrations/001_create_items.sql | Skema awal tabel items |
tests/integration_test.go | Test black-box HTTP |
Dockerfile | Build multi-stage (builder Go → runtime Alpine) |
compose.yaml | Service app, db, dan test (profile) |
.dockerignore | Membatasi build context |
Endpoint #
| Metode | Path | Keterangan |
|---|---|---|
| GET | /healthz | Cek kesehatan aplikasi dan database |
| GET | /api/items | Daftar seluruh item |
| POST | /api/items | Buat item baru (body: name, note) |
| GET | /api/items/{id} | Ambil satu item (404 jika tidak ada) |
Menjalankan #
Password database diambil dari environment; paling mudah lewat berkas .env:
bash
echo 'POSTGRES_PASSWORD=rahasia123' > .env
docker compose up -d --buildMenguji #
bash
curl -s http://localhost:8080/healthz
curl -s -X POST http://localhost:8080/api/items \
-H 'Content-Type: application/json' \
-d '{"name":"Kopi Torabika","note":"favorit pelanggan"}'
curl -s http://localhost:8080/api/items
curl -s http://localhost:8080/api/items/1Hasil yang diharapkan: healthz mengembalikan {"status":"ok"}, POST
mengembalikan 201 dengan item ber-id 1, daftar memuat item tersebut, dan
GET /api/items/999 mengembalikan 404.
Integration Test #
Test menembak HTTP aplikasi dari container golang terpisah dengan profile
test (aplikasi dan database tetap berjalan):
bash
docker compose --profile test run --rm testMembersihkan #
bash
docker compose down # volume db-data tetap ada
docker compose down -v # sekaligus menghapus data