perbaikan generete tool
This commit is contained in:
438
README.md
438
README.md
@@ -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.
|
||||
|
||||
## 🚀 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
|
||||
## 📋 Quick Start (5 Menit)
|
||||
|
||||
### 1. Setup Environment
|
||||
```bash
|
||||
git clone <repository-url>
|
||||
cd api-service
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
### 2. Environment Configuration
|
||||
|
||||
Create a `.env` file in the project root:
|
||||
|
||||
### 2. Jalankan Database & API
|
||||
```bash
|
||||
# Server Configuration
|
||||
PORT=8080
|
||||
GIN_MODE=debug
|
||||
# Opsi A: Docker (Rekomendasi)
|
||||
make docker-run
|
||||
|
||||
# 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_PORT=5432
|
||||
BLUEPRINT_DB_USERNAME=postgres
|
||||
BLUEPRINT_DB_PASSWORD=postgres
|
||||
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
|
||||
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
|
||||
make docker-run
|
||||
make docker-run # Jalankan semua services
|
||||
docker-compose down # Stop services
|
||||
```
|
||||
|
||||
#### Option B: Manual PostgreSQL Setup
|
||||
```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
|
||||
### Production
|
||||
```bash
|
||||
docker build -t api-service:prod .
|
||||
docker run -d -p 8080:8080 --env-file .env api-service:prod
|
||||
```
|
||||
|
||||
### Health Check
|
||||
## 🎯 Tips Cepat
|
||||
|
||||
### 1. Generate CRUD Lengkap
|
||||
```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
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `PORT` | 8080 | Server port |
|
||||
| `GIN_MODE` | debug | Gin mode (debug/release/test) |
|
||||
### 3. Debug Database
|
||||
- **pgAdmin**: http://localhost:5050
|
||||
- **Database**: api_service
|
||||
- **User/Pass**: postgres/postgres
|
||||
|
||||
### Database Configuration
|
||||
| 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 |
|
||||
## 🚨 Troubleshooting
|
||||
|
||||
### Keycloak Configuration
|
||||
| Variable | Default | Description |
|
||||
|----------|---------|-------------|
|
||||
| `KEYCLOAK_ISSUER` | - | Keycloak issuer URL |
|
||||
| `KEYCLOAK_AUDIENCE` | - | Keycloak audience/client ID |
|
||||
| `KEYCLOAK_JWKS_URL` | - | Keycloak JWKS URL |
|
||||
| `KEYCLOAK_ENABLED` | true | Enable/disable Keycloak auth |
|
||||
### Generate Handler Gagal
|
||||
- Pastikan di root project
|
||||
- Cek file `internal/routes/v1/routes.go` ada
|
||||
- Pastikan permission write
|
||||
|
||||
## 🤝 Contributing
|
||||
### Database Connection Error
|
||||
- Cek PostgreSQL running
|
||||
- Verifikasi .env configuration
|
||||
- Gunakan `make docker-run` untuk setup otomatis
|
||||
|
||||
1. Fork the repository
|
||||
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
|
||||
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
|
||||
4. Push to the branch (`git push origin feature/amazing-feature`)
|
||||
5. Open a Pull Request
|
||||
### Token Invalid
|
||||
- Login ulang untuk dapat token baru
|
||||
- Token expire dalam 1 jam
|
||||
- Pastikan format: `Bearer <token>`
|
||||
|
||||
## 📄 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
|
||||
- [Swagger](https://swagger.io/) - API documentation
|
||||
- [Testcontainers](https://testcontainers.com/) - Integration testing
|
||||
---
|
||||
**Total waktu setup: 5 menit** | **Generate CRUD: 30 detik** | **Testing: Langsung di Swagger**
|
||||
|
||||
Reference in New Issue
Block a user