diff --git a/AUTHENTICATION.md b/AUTHENTICATION.md deleted file mode 100644 index fc308601..00000000 --- a/AUTHENTICATION.md +++ /dev/null @@ -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 -``` - -#### GET /api/v1/auth/me -Get information about the currently authenticated user. - -**Headers:** -``` -Authorization: Bearer -``` - -**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 " - -# Get products -curl -X GET http://localhost:8080/api/v1/products \ - -H "Authorization: Bearer " -``` - -## 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 diff --git a/LAYOUT.md b/LAYOUT.md deleted file mode 100644 index 18b21ccd..00000000 --- a/LAYOUT.md +++ /dev/null @@ -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 -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 diff --git a/README.md b/README.md index 7348a1a5..20a762f5 100644 --- a/README.md +++ b/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 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 " +``` + +### 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 -``` - -## ๐Ÿงช 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 ` -## ๐Ÿ“„ 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** diff --git a/tools/HANDLER.md b/tools/HANDLER.md deleted file mode 100644 index 584b35ad..00000000 --- a/tools/HANDLER.md +++ /dev/null @@ -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 [methods] - -# Contoh: -generate.bat user get post -generate.bat product get post put delete -``` - -### Linux/Mac -```bash -# Buka terminal di folder tools -./generate.sh [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 [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//.go` -2. **Models**: `internal/models//.go` -3. **Routes**: Update otomatis di `internal/routes/v1/routes.go` - - ****: `Nama Directori` - - **.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//.go`) -- Struct handler -- Constructor function -- Endpoint methods dengan swagger documentation -- Error handling -- Import models dari `api-service/internal/models/` - -### Model File (`internal/models//.go`) -- Request models -- Response models -- Error response models -- Package name sesuai dengan nama handler - -### Routes Update -- Otomatis menambahkan routes ke `/api/v1/` -- 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 diff --git a/tools/diagnostic.go b/tools/diagnostic.go deleted file mode 100644 index cb564042..00000000 --- a/tools/diagnostic.go +++ /dev/null @@ -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.") -}