perbaikan generete tool

This commit is contained in:
2025-08-18 12:37:05 +07:00
parent 27924aeb3c
commit ed760a52b5
5 changed files with 169 additions and 978 deletions

View File

@@ -1,141 +0,0 @@
# JWT Authentication API Documentation
This document describes how to use the JWT authentication system implemented in this API service.
## Overview
The API provides JWT-based authentication with the following features:
- User login with username/password
- JWT token generation
- Token validation middleware
- Protected routes
- User registration
## Endpoints
### Public Endpoints (No Authentication Required)
#### POST /api/v1/auth/login
Login with username and password to receive a JWT token.
**Request Body:**
```json
{
"username": "admin",
"password": "password"
}
```
**Response:**
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"token_type": "Bearer",
"expires_in": 3600
}
```
#### POST /api/v1/auth/register
Register a new user account.
**Request Body:**
```json
{
"username": "newuser",
"email": "user@example.com",
"password": "securepassword",
"role": "user"
}
```
**Response:**
```json
{
"message": "user registered successfully"
}
```
### Protected Endpoints (Authentication Required)
All protected endpoints require a valid JWT token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```
#### GET /api/v1/auth/me
Get information about the currently authenticated user.
**Headers:**
```
Authorization: Bearer <your-jwt-token>
```
**Response:**
```json
{
"id": "1",
"username": "admin",
"email": "admin@example.com",
"role": "admin"
}
```
## Demo Users
The system comes with pre-configured demo users:
| Username | Password | Role |
|----------|----------|-------|
| admin | password | admin |
| user | password | user |
## Using the JWT Token
Once you receive a JWT token from the login endpoint, include it in the Authorization header for all protected endpoints:
```bash
curl -X GET http://localhost:8080/api/v1/products \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
```
## Token Expiration
JWT tokens expire after 1 hour. When a token expires, you'll need to login again to get a new token.
## Environment Variables
To configure JWT authentication, you can set these environment variables:
```bash
# JWT Secret (change this in production)
JWT_SECRET=your-secret-key-change-this-in-production
```
## Testing the Authentication
### 1. Login with demo user
```bash
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"password"}'
```
### 2. Use the token to access protected endpoints
```bash
# Get user info
curl -X GET http://localhost:8080/api/v1/auth/me \
-H "Authorization: Bearer <your-token>"
# Get products
curl -X GET http://localhost:8080/api/v1/products \
-H "Authorization: Bearer <your-token>"
```
## Error Handling
The API returns appropriate HTTP status codes:
- `200 OK` - Successful request
- `201 Created` - Resource created successfully
- `400 Bad Request` - Invalid request data
- `401 Unauthorized` - Invalid or missing token
- `500 Internal Server Error` - Server error

289
LAYOUT.md
View File

@@ -1,289 +0,0 @@
# 📊 API Service Project Layout
## 🎯 Project Overview Dashboard
### 📈 Key Metrics
- **Language**: Go 1.24.4
- **Framework**: Gin 1.10.1
- **Database**: PostgreSQL with GORM
- **Authentication**: JWT + Keycloak
- **Documentation**: Swagger/OpenAPI 3.0
- **Container**: Docker & Docker Compose
### 🏗️ Architecture Overview
```
api-service/
├── cmd/
│ └── api/
│ └── main.go
├── internal/
│ ├── config/ # Config loader
│ ├── server/ # HTTP server setup + routes binding
│ ├── handler/ # HTTP handlers (controller layer)
│ ├── service/ # Business logic
│ ├── repository/ # DB access layer
│ ├── model/ # App/domain models
│ └── middleware/ # HTTP middlewares
├── pkg/ # Reusable packages independent of business logic
│ ├── logger/
│ ├── utils/
│ └── validator/
├── scripts/ # Deployment & build automation
└── docs/ # Documentation (incl. swagger)
```
## 🚀 Development Environment Layout
### 📋 Prerequisites Setup
```bash
# Required tools
- Go 1.24.4+
- PostgreSQL 12+
- Docker & Docker Compose
- Keycloak Server (optional)
# Development tools
- Air (hot reload)
- Swag (Swagger docs)
- Make (build automation)
```
### 🔧 Configuration Files Layout
```
project-root/
├── .env # Environment variables
├── .air.toml # Air configuration
├── Makefile # Build commands
├── docker-compose.yml # Docker services
├── Dockerfile # Container image
└── .goreleaser.yml # Release configuration
```
## 📚 API Documentation Layout
### 🌐 Base URL Structure
```
http://localhost:8080/api/v1
```
### 📖 Endpoint Categories
#### 🔍 Health & Monitoring
- `GET /api/v1/health` - Health check
- `GET /api/v1/` - Hello world
- `GET /api/v1/metrics` - Application metrics
#### 🔐 Authentication Endpoints
- `POST /api/v1/auth/login` - User login
- `POST /api/v1/auth/register` - User registration
- `POST /api/v1/auth/refresh` - Token refresh
- `POST /api/v1/auth/logout` - User logout
#### 👤 User Management
- `GET /api/v1/users/profile` - Get user profile
- `PUT /api/v1/users/profile` - Update user profile
- `GET /api/v1/users` - List users (admin)
- `GET /api/v1/users/:id` - Get user by ID
#### 📦 Product Management
- `GET /api/v1/products` - List products
- `POST /api/v1/products` - Create product
- `GET /api/v1/products/:id` - Get product
- `PUT /api/v1/products/:id` - Update product
- `DELETE /api/v1/products/:id` - Delete product
#### 🔄 Real-time Features
- `GET /api/v1/websocket` - WebSocket connection
- `GET /api/v1/webservice` - Web service endpoint
### 📊 Swagger Documentation
- **Interactive UI**: http://localhost:8080/swagger/index.html
- **OpenAPI JSON**: http://localhost:8080/swagger/doc.json
## 🐳 Docker Deployment Layout
### 🏃 Development Environment
```bash
# Start all services
make docker-run
# Services included:
- PostgreSQL database
- API service with hot reload
- pgAdmin (database management)
```
### 🚀 Production Environment
```bash
# Build production image
docker build -t api-service:prod .
# Run production container
docker run -d \
-p 8080:8080 \
--env-file .env \
--name api-service \
api-service:prod
```
### 📦 Docker Compose Services
```yaml
services:
postgres:
image: postgres:15-alpine
environment:
POSTGRES_DB: api_service
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
ports:
- "5432:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
api:
build: .
ports:
- "8080:8080"
depends_on:
- postgres
environment:
- BLUEPRINT_DB_HOST=postgres
volumes:
- .:/app
command: air -c .air.toml
```
## 🛠️ Development Workflow Layout
### 🔄 Daily Development Cycle
```bash
# 1. Start development environment
make watch
# 2. Run tests
make test
# 3. Check code quality
make lint
# 4. Build for production
make build
```
### 🧪 Testing Strategy
```
tests/
├── unit/ # Unit tests
├── integration/ # Integration tests
├── e2e/ # End-to-end tests
└── fixtures/ # Test data
```
### 📊 Monitoring & Logging
- **Health Check**: `/api/v1/health`
- **Metrics**: Prometheus metrics
- **Logging**: Structured JSON logs
- **Tracing**: Distributed tracing support
## 📁 File Structure Detailed Layout
### 📄 Configuration Files
```
.env.example # Environment template
config/
├── config.go # Configuration struct
├── config_test.go # Configuration tests
└── validation.go # Config validation
```
### 🗄️ Database Layout
```
database/
├── migrations/ # Database migrations
├── seeds/ # Seed data
├── models/ # GORM models
└── repositories/ # Data access layer
```
### 🎯 Handler Layout
```
handlers/
├── auth.go # Authentication handlers
├── user.go # User management handlers
├── product.go # Product handlers
├── health.go # Health check handlers
└── middleware/ # HTTP middleware
├── auth.go # JWT middleware
├── cors.go # CORS middleware
└── logger.go # Logging middleware
```
### 🌐 Route Layout
```
routes/
├── v1/
│ ├── routes.go # Route definitions
│ ├── auth_routes.go # Auth routes
│ ├── user_routes.go # User routes
│ └── product_routes.go # Product routes
└── middleware.go # Route middleware
```
## 🚀 Quick Start Commands
### 🏃 Development
```bash
# Clone and setup
git clone <repo-url>
cd api-service
cp .env.example .env
make docker-run
# Start development
make watch
```
### 🧪 Testing
```bash
# Run all tests
make all
# Run specific test
make test
make itest
```
### 🚀 Production
```bash
# Build and run
make build
./main.exe
```
## 📊 Performance Monitoring Layout
### 📈 Metrics Collection
- **Request Duration**: Track API response times
- **Error Rates**: Monitor error frequencies
- **Database Performance**: Query execution times
- **Memory Usage**: Application memory consumption
### 🔍 Health Checks
- **Database Connectivity**: PostgreSQL connection status
- **External Services**: Keycloak availability
- **Resource Usage**: CPU and memory utilization
## 🎯 Next Steps
1. **Setup Environment**: Copy `.env.example` to `.env`
2. **Start Database**: Run `make docker-run`
3. **Start Development**: Run `make watch`
4. **Test API**: Visit `http://localhost:8080/swagger/index.html`
5. **Run Tests**: Execute `make all`
## 📞 Support & Resources
- **Documentation**: Check `/docs` folder
- **API Testing**: Use Swagger UI at `/swagger/index.html`
- **Database**: Access pgAdmin at `http://localhost:5050`
- **Issues**: Create GitHub issues for bugs/features

438
README.md
View File

@@ -1,311 +1,211 @@
# API Service # 🚀 API Service Guide
A comprehensive Go-based REST API service built with Gin framework, featuring PostgreSQL database integration, JWT authentication, Swagger documentation, WebSocket support, and containerized deployment. ## 📋 Quick Start (5 Menit)
## 🚀 Features
- **RESTful API** with Gin framework
- **PostgreSQL** database integration with GORM
- **JWT Authentication** with Keycloak integration
- **Swagger/OpenAPI** documentation
- **WebSocket** real-time communication support
- **Docker** containerization
- **Graceful shutdown** handling
- **CORS** support
- **Error handling** middleware
- **Live reload** with Air for development
- **Comprehensive testing** with integration tests
## 🏗️ Architecture
```
api-service/
├── cmd/api/ # Application entry point
├── internal/
│ ├── config/ # Configuration management
│ ├── database/ # Database connection and models
│ ├── handlers/ # HTTP request handlers
│ ├── middleware/ # HTTP middleware
│ ├── models/ # Data models
│ ├── routes/ # Route definitions
│ └── server/ # HTTP server setup
├── docker-compose.yml # Docker services configuration
├── Dockerfile # Container image definition
├── Makefile # Build automation
└── go.mod # Go module dependencies
```
## 🛠️ Technology Stack
- **Language**: Go 1.24.4
- **Web Framework**: Gin 1.10.1
- **Database**: PostgreSQL with GORM
- **Authentication**: JWT with Keycloak
- **Documentation**: Swagger/OpenAPI 3.0
- **WebSocket**: gorilla/websocket
- **Testing**: Testcontainers for integration tests
- **Containerization**: Docker & Docker Compose
- **Hot Reload**: Air for development
## 📋 Prerequisites
- Go 1.24.4 or higher
- PostgreSQL 12 or higher
- Docker & Docker Compose (optional)
- Keycloak server (for authentication)
## 🔧 Installation & Setup
### 1. Clone the Repository
### 1. Setup Environment
```bash ```bash
git clone <repository-url> git clone <repository-url>
cd api-service cd api-service
cp .env.example .env
``` ```
### 2. Environment Configuration ### 2. Jalankan Database & API
Create a `.env` file in the project root:
```bash ```bash
# Server Configuration # Opsi A: Docker (Rekomendasi)
PORT=8080 make docker-run
GIN_MODE=debug
# Database Configuration # Opsi B: Manual
go mod download
go run cmd/api/main.go
```
### 3. Akses API
- **API**: http://localhost:8080/api/v1
- **Swagger**: http://localhost:8080/swagger/index.html
- **Health Check**: http://localhost:8080/api/v1/health
## 🏗️ Struktur Project
```
api-service/
├── cmd/api/main.go # Entry point
├── internal/ # Core business logic
│ ├── handlers/ # HTTP controllers
│ ├── models/ # Data structures
│ ├── middleware/ # Auth & error handling
│ └── routes/ # API routes
├── tools/ # CLI generators
└── docs/ # API documentation
```
## 🔐 Authentication
### Login (Dapatkan Token)
```bash
curl -X POST http://localhost:8080/api/v1/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"password"}'
```
### Gunakan Token
```bash
curl -X GET http://localhost:8080/api/v1/products \
-H "Authorization: Bearer <your-token>"
```
### Demo Users
| Username | Password | Role |
|----------|----------|------|
| admin | password | admin |
| user | password | user |
## 🛠️ Generate Handler Baru (30 Detik)
### Cara Cepat
```bash
# Windows
tools/generate.bat product get post put delete
# Linux/Mac
./tools/generate.sh product get post put delete
# Atau langsung dengan Go
go run tools/generate-handler.go product get post
go run tools/ generate-handler.go order get post put delete stats
```
### Method Tersedia
- `get` - Ambil data
- `post` - Buat data baru
- `put` - Update data
- `delete` - Hapus data
### Hasil Generate
- **Handler**: `internal/handlers/product/product.go`
- **Models**: `internal/models/product/product.go`
- **Routes**: Otomatis ditambahkan ke `/api/v1/products`
## 📊 API Endpoints
### Public (Tanpa Auth)
- `POST /api/v1/auth/login` - Login
- `POST /api/v1/auth/register` - Register
- `GET /api/v1/health` - Health check
### Protected (Dengan Auth)
- `GET /api/v1/auth/me` - Profile user
- `GET /api/v1/products` - List products
- `POST /api/v1/products` - Create product
- `GET /api/v1/products/:id` - Detail product
- `PUT /api/v1/products/:id` - Update product
- `DELETE /api/v1/products/:id` - Delete product
## 🧪 Development Workflow
### Perintah Penting
```bash
make watch # Jalankan dengan hot reload
make test # Unit tests
make itest # Integration tests
make all # Semua tests
make build # Build production
```
### Update Swagger
```bash
swag init -g cmd/api/main.go --parseDependency --parseInternal
```
## 🔧 Environment Variables
### Database
```bash
BLUEPRINT_DB_HOST=localhost BLUEPRINT_DB_HOST=localhost
BLUEPRINT_DB_PORT=5432 BLUEPRINT_DB_PORT=5432
BLUEPRINT_DB_USERNAME=postgres BLUEPRINT_DB_USERNAME=postgres
BLUEPRINT_DB_PASSWORD=postgres BLUEPRINT_DB_PASSWORD=postgres
BLUEPRINT_DB_DATABASE=api_service BLUEPRINT_DB_DATABASE=api_service
BLUEPRINT_DB_SCHEMA=public
# Keycloak Configuration
KEYCLOAK_ISSUER=https://keycloak.example.com/auth/realms/yourrealm
KEYCLOAK_AUDIENCE=your-client-id
KEYCLOAK_JWKS_URL=https://keycloak.example.com/auth/realms/yourrealm/protocol/openid-connect/certs
KEYCLOAK_ENABLED=true
``` ```
### 3. Install Dependencies ### JWT Secret
```bash ```bash
go mod download JWT_SECRET=your-secret-key-change-this-in-production
``` ```
### 4. Database Setup ## 🐳 Docker Commands
#### Option A: Using Docker Compose (Recommended) ### Development
```bash ```bash
make docker-run make docker-run # Jalankan semua services
docker-compose down # Stop services
``` ```
#### Option B: Manual PostgreSQL Setup ### Production
```bash
# Create database
createdb api_service
# Run migrations (if any)
# go run cmd/migrate/main.go
```
### 5. Run the Application
#### Development Mode (with hot reload)
```bash
make watch
```
#### Production Mode
```bash
make build
./main.exe
```
## 🌐 API Endpoints
### Base URL
```
http://localhost:8080/api/v1
```
### Health Check
- `GET /api/v1/health` - Health check endpoint
- `GET /api/v1/` - Hello world endpoint
### Example Endpoints
- `GET /api/v1/example` - Get example data
- `POST /api/v1/example` - Create example data
### WebSocket
- `GET /api/v1/websocket` - WebSocket endpoint
- `GET /api/v1/webservice` - Web service endpoint
### Swagger Documentation
- `GET /swagger/index.html` - Interactive API documentation
## 🔐 Authentication
The API uses JWT tokens for authentication. Include the token in the Authorization header:
```
Authorization: Bearer <your-jwt-token>
```
## 🧪 Testing
### Unit Tests
```bash
make test
```
### Integration Tests
```bash
make itest
```
### Run All Tests
```bash
make all
```
## 🐳 Docker Deployment
### Build and Run with Docker Compose
```bash
# Development
make docker-run
# Production
docker-compose -f docker-compose.yml up --build -d
```
### Docker Commands
```bash
# Build image
docker build -t api-service .
# Run container
docker run -p 8080:8080 --env-file .env api-service
```
## 📊 Monitoring & Logging
- **Health Check**: `/api/v1/health`
- **Metrics**: Available through middleware
- **Logging**: Structured logging with Gin
## 🔄 Development Workflow
1. **Feature Development**
```bash
git checkout -b feature/your-feature
make watch # Start development server with hot reload
```
2. **Testing**
```bash
make test
make itest
```
3. **Code Quality**
```bash
go fmt ./...
go vet ./...
```
4. **Build & Run**
```bash
make build
make run
```
## 📝 API Documentation
After starting the server, visit:
- Swagger UI: http://localhost:8080/swagger/index.html
- OpenAPI JSON: http://localhost:8080/swagger/doc.json
### CLI Command to Generate Swagger Documentation
Generate Swagger documentation using the following command:
```bash
swag init -g cmd/api/main.go --output docs
```
This command will:
- Scan your Go source code for Swagger annotations
- Generate OpenAPI 3.0 specification files
- Create/update the documentation in `docs/` directory
- Include all API endpoints, models, and authentication details
Make sure to run this command whenever you add new endpoints or modify existing API documentation.
## 🚀 Production Deployment
### Environment Variables
Set the following for production:
```bash
GIN_MODE=release
PORT=8080
```
### Docker Production
```bash ```bash
docker build -t api-service:prod . docker build -t api-service:prod .
docker run -d -p 8080:8080 --env-file .env api-service:prod docker run -d -p 8080:8080 --env-file .env api-service:prod
``` ```
### Health Check ## 🎯 Tips Cepat
### 1. Generate CRUD Lengkap
```bash ```bash
curl -f http://localhost:8080/api/v1/health || exit 1 go run tools/generate-handler.go user get post put delete
``` ```
## 🔧 Configuration ### 2. Test API dengan Swagger
1. Buka http://localhost:8080/swagger/index.html
2. Login untuk dapat token
3. Klik "Authorize" dan masukkan token
4. Test semua endpoint
### Server Configuration ### 3. Debug Database
| Variable | Default | Description | - **pgAdmin**: http://localhost:5050
|----------|---------|-------------| - **Database**: api_service
| `PORT` | 8080 | Server port | - **User/Pass**: postgres/postgres
| `GIN_MODE` | debug | Gin mode (debug/release/test) |
### Database Configuration ## 🚨 Troubleshooting
| Variable | Default | Description |
|----------|---------|-------------|
| `BLUEPRINT_DB_HOST` | localhost | Database host |
| `BLUEPRINT_DB_PORT` | 5432 | Database port |
| `BLUEPRINT_DB_USERNAME` | postgres | Database username |
| `BLUEPRINT_DB_PASSWORD` | postgres | Database password |
| `BLUEPRINT_DB_DATABASE` | api_service | Database name |
| `BLUEPRINT_DB_SCHEMA` | public | Database schema |
### Keycloak Configuration ### Generate Handler Gagal
| Variable | Default | Description | - Pastikan di root project
|----------|---------|-------------| - Cek file `internal/routes/v1/routes.go` ada
| `KEYCLOAK_ISSUER` | - | Keycloak issuer URL | - Pastikan permission write
| `KEYCLOAK_AUDIENCE` | - | Keycloak audience/client ID |
| `KEYCLOAK_JWKS_URL` | - | Keycloak JWKS URL |
| `KEYCLOAK_ENABLED` | true | Enable/disable Keycloak auth |
## 🤝 Contributing ### Database Connection Error
- Cek PostgreSQL running
- Verifikasi .env configuration
- Gunakan `make docker-run` untuk setup otomatis
1. Fork the repository ### Token Invalid
2. Create your feature branch (`git checkout -b feature/amazing-feature`) - Login ulang untuk dapat token baru
3. Commit your changes (`git commit -m 'Add some amazing feature'`) - Token expire dalam 1 jam
4. Push to the branch (`git push origin feature/amazing-feature`) - Pastikan format: `Bearer <token>`
5. Open a Pull Request
## 📄 License ## 📱 Contoh Integrasi Frontend
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details. ### JavaScript/Axios
```javascript
// Login
const login = await axios.post('/api/v1/auth/login', {
username: 'admin',
password: 'password'
});
## 🆘 Support // Set token
axios.defaults.headers.common['Authorization'] =
`Bearer ${login.data.access_token}`;
For support, email support@example.com or create an issue in the GitHub repository. // Get data
const products = await axios.get('/api/v1/products');
```
## 🙏 Acknowledgments ## 🎉 Next Steps
1. ✅ Setup environment selesai
2. ✅ Generate handler pertama
3. ✅ Test dengan Swagger
4. 🔄 Tambahkan business logic
5. 🔄 Deploy ke production
- [Gin](https://github.com/gin-gonic/gin) - HTTP web framework ---
- [GORM](https://gorm.io/) - ORM for Go **Total waktu setup: 5 menit** | **Generate CRUD: 30 detik** | **Testing: Langsung di Swagger**
- [Swagger](https://swagger.io/) - API documentation
- [Testcontainers](https://testcontainers.com/) - Integration testing

View File

@@ -1,149 +0,0 @@
# Handler Generator CLI Tool
CLI tool untuk generate handler baru secara otomatis dengan swagger documentation.
## Cara Penggunaan
### Windows
```bash
# Buka terminal di folder tools
generate.bat <nama-handler> [methods]
# Contoh:
generate.bat user get post
generate.bat product get post put delete
```
### Linux/Mac
```bash
# Buka terminal di folder tools
./generate.sh <nama-handler> [methods]
# Contoh:
./generate.sh user get post
./generate.sh product get post put delete
```
### Langsung dengan Go
```bash
# Dari root project
go run tools/generate-handler.go <nama-handler> [methods]
# Contoh:
go run tools/generate-handler.go user get post put delete
go run tools/generate-handler.go product get post
go run tools/ generate-handler.go order get post put delete stats
```
## Method yang Tersedia
- `get` - GET endpoint untuk list data
- `post` - POST endpoint untuk create data
- `put` - PUT endpoint untuk update data
- `delete` - DELETE endpoint untuk delete data
## File yang Dibuat Otomatis
1. **Handler**: `internal/handlers/<nama>/<nama>.go`
2. **Models**: `internal/models/<nama>/<nama>.go`
3. **Routes**: Update otomatis di `internal/routes/v1/routes.go`
- **<nama>**: `Nama Directori`
- **<nama>.go**: `Nama file class`
## Contoh Penggunaan
### 1. Generate Handler dengan GET dan POST
```bash
./generate.sh user get post
```
### 2. Generate Handler dengan semua method
```bash
./generate.sh product get post put delete
```
### 3. Generate Handler dengan custom method
```bash
./generate.sh order get post delete
```
## Langkah Setelah Generate
1. Jalankan swagger generator:
```bash
swag init -g cmd/api/main.go --parseDependency --parseInternal
```
2. Jalankan aplikasi:
```bash
go run cmd/api/main.go
```
3. Akses swagger UI:
```
http://localhost:8080/swagger/index.html
```
## Struktur File yang Dibuat
### Handler File (`internal/handlers/<nama>/<nama>.go`)
- Struct handler
- Constructor function
- Endpoint methods dengan swagger documentation
- Error handling
- Import models dari `api-service/internal/models/<nama>`
### Model File (`internal/models/<nama>/<nama>.go`)
- Request models
- Response models
- Error response models
- Package name sesuai dengan nama handler
### Routes Update
- Otomatis menambahkan routes ke `/api/v1/<nama-plural>`
- Support parameter ID untuk endpoint spesifik
- Menggunakan componentHandlers untuk handler baru
## Contoh Output
Untuk command: `./generate.sh user get post`
### Handler yang dibuat:
- `GET /api/v1/users` - List users
- `GET /api/v1/users/:id` - Get user by ID
- `POST /api/v1/users` - Create new user
### Struktur Direktori:
```
internal/
├── handlers/
│ └── user/
│ └── user.go
├── models/
│ └── user/
│ └── user.go
```
### Swagger Documentation
Semua endpoint otomatis memiliki swagger documentation yang bisa diakses di:
```
http://localhost:8080/swagger/index.html
```
## Tips Penggunaan
1. **Nama Handler**: Gunakan nama singular (user, product, order)
2. **Method**: Pilih method sesuai kebutuhan CRUD
3. **Custom Fields**: Edit file models yang dibuat untuk menambahkan custom fields
4. **Service Layer**: Tambahkan service layer untuk business logic yang kompleks
5. **Repository Layer**: Tambahkan repository layer untuk database operations
## Troubleshooting
### Jika generate gagal:
- Pastikan berada di root project
- Pastikan file `internal/routes/v1/routes.go` ada
- Pastikan permission untuk menulis file
### Jika routes tidak muncul:
- Cek file `internal/routes/v1/routes.go` untuk duplikasi nama handler
- Pastikan tidak ada nama handler yang sama dengan yang sudah ada

View File

@@ -1,130 +0,0 @@
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/jackc/pgx/v5"
"github.com/joho/godotenv"
)
func maindiagnostic() {
fmt.Println("=== Database Connection Diagnostic Tool ===")
// Load environment variables from .env file
if err := godotenv.Load(); err != nil {
log.Printf("Warning: Error loading .env file: %v", err)
}
// Get configuration from environment
host := os.Getenv("DB_HOST")
port := os.Getenv("DB_PORT")
username := os.Getenv("DB_USERNAME")
password := os.Getenv("DB_PASSWORD")
database := os.Getenv("DB_DATABASE")
sslmode := os.Getenv("DB_SSLMODE")
if sslmode == "" {
sslmode = "disable"
}
fmt.Printf("Host: %s\n", host)
fmt.Printf("Port: %s\n", port)
fmt.Printf("Username: %s\n", username)
fmt.Printf("Database: %s\n", database)
fmt.Printf("SSL Mode: %s\n", sslmode)
if host == "" || username == "" || password == "" {
fmt.Println("❌ Missing required environment variables")
return
}
// Test connection to PostgreSQL server
fmt.Println("\n--- Testing PostgreSQL Server Connection ---")
serverConnStr := fmt.Sprintf("postgres://%s:%s@%s:%s/postgres?sslmode=%s",
username, password, host, port, sslmode)
db, err := sql.Open("pgx", serverConnStr)
if err != nil {
fmt.Printf("❌ Failed to connect to PostgreSQL server: %v\n", err)
return
}
defer db.Close()
err = db.Ping()
if err != nil {
fmt.Printf("❌ Failed to ping PostgreSQL server: %v\n", err)
return
}
fmt.Println("✅ Successfully connected to PostgreSQL server")
// Check if database exists
fmt.Println("\n--- Checking Database Existence ---")
var exists bool
err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM pg_database WHERE datname = $1)", database).Scan(&exists)
if err != nil {
fmt.Printf("❌ Failed to check database existence: %v\n", err)
return
}
if !exists {
fmt.Printf("❌ Database '%s' does not exist\n", database)
// List available databases
fmt.Println("\n--- Available Databases ---")
rows, err := db.Query("SELECT datname FROM pg_database WHERE datistemplate = false ORDER BY datname")
if err != nil {
fmt.Printf("❌ Failed to list databases: %v\n", err)
return
}
defer rows.Close()
fmt.Println("Available databases:")
for rows.Next() {
var dbName string
if err := rows.Scan(&dbName); err != nil {
continue
}
fmt.Printf(" - %s\n", dbName)
}
return
}
fmt.Printf("✅ Database '%s' exists\n", database)
// Test direct connection to the database
fmt.Println("\n--- Testing Direct Database Connection ---")
directConnStr := fmt.Sprintf("postgres://%s:%s@%s:%s/%s?sslmode=%s",
username, password, host, port, database, sslmode)
targetDB, err := sql.Open("pgx", directConnStr)
if err != nil {
fmt.Printf("❌ Failed to connect to database '%s': %v\n", database, err)
return
}
defer targetDB.Close()
err = targetDB.Ping()
if err != nil {
fmt.Printf("❌ Failed to ping database '%s': %v\n", database, err)
return
}
fmt.Printf("✅ Successfully connected to database '%s'\n", database)
// Test basic query
fmt.Println("\n--- Testing Basic Query ---")
var version string
err = targetDB.QueryRow("SELECT version()").Scan(&version)
if err != nil {
fmt.Printf("❌ Failed to execute query: %v\n", err)
return
}
fmt.Printf("✅ PostgreSQL Version: %s\n", version)
fmt.Println("\n🎉 All tests passed! Database connection is working correctly.")
}