9119e2383e
- Introduced a new `config.yaml` file for managing server, database, cache, queue, AI, scraping, logging, and rate limiting configurations. - Updated `docker-compose.yml` to reflect the new server port (8081) and adjusted health check endpoints accordingly. - Modified `Dockerfile` to expose the new server port. - Updated `README.md` to reflect changes in server configuration and added documentation for the new configuration structure. - Added test scripts for server and Swagger documentation testing. - Refactored customer domain structure to align with new configuration settings and improve maintainability.
6.4 KiB
6.4 KiB
HTTP Server Setup and Dependency Injection
Overview
The Tender Management API server has been successfully initialized with proper dependency injection following Clean Architecture principles. The server uses Echo v4 as the HTTP framework and implements a complete dependency injection chain.
Architecture
Dependency Injection Chain
MongoDB Connection Manager
↓
Repositories
↓
Services
↓
Handlers
↓
HTTP Server (Echo)
Components
-
MongoDB Connection Manager (
pkg/mongo/connection.go)- Manages database connections and pooling
- Provides connection to repositories
-
Repositories (
internal/customer/repository.go)- Data access layer
- Implements repository pattern
- Handles database operations
-
Services (
internal/customer/service.go)- Business logic layer
- Implements use cases
- Depends on repositories
-
Handlers (
internal/customer/handler.go)- HTTP request/response handling
- Input validation
- Depends on services
-
HTTP Server (
cmd/web/main.go)- Echo v4 server with middleware
- Route registration
- Server lifecycle management
Server Features
Middleware Stack
- Recover - Panic recovery
- RequestID - Unique request identification
- Logger - Request logging
- CORS - Cross-origin resource sharing
- Custom Logging - Structured request logging
Endpoints
Health Check
GET /health- Server health status
Customer Endpoints
POST /api/customers/login- Customer loginPOST /api/customers/refresh-token- Token refreshGET /api/customers/profile- Get profile (protected)PUT /api/customers/profile- Update profile (protected)PUT /api/customers/change-password- Change password (protected)POST /api/customers/device-token- Add device token (protected)DELETE /api/customers/device-token- Remove device token (protected)POST /api/customers/logout- Logout (protected)
Admin Endpoints
POST /api/admin/customers/register- Register customer (admin)GET /api/admin/customers- List customers (admin)GET /api/admin/customers/:id- Get customer by ID (admin)PUT /api/admin/customers/:id/status- Update customer status (admin)GET /api/admin/customers/device-tokens- Get all device tokens (admin)
Configuration
Server Configuration (config.yaml)
server:
host: "0.0.0.0"
port: 8081
timeout: 30s
read_timeout: 10s
write_timeout: 10s
Database Configuration
database:
mongodb:
uri: "mongodb://localhost:27017"
name: "tender_management"
timeout: 10s
max_pool_size: 100
Running the Server
Prerequisites
- MongoDB - Must be running locally or accessible
- Go 1.23+ - Required for compilation
- Configuration -
config.yamlmust be present
Build and Run
# Build the server
go build -o bin/web ./cmd/web
# Run the server
./bin/web
Development
# Run with hot reload (if using air)
air
# Or run directly
go run ./cmd/web
Testing
Health Check
curl http://localhost:8081/health
Expected response:
{
"status": "healthy",
"time": 1703123456,
"version": "1.0.0"
}
Customer Registration
curl -X POST http://localhost:8081/api/admin/customers/register \
-H "Content-Type: application/json" \
-d '{
"full_name": "John Doe",
"username": "johndoe",
"email": "john@example.com",
"mobile": "+1234567890",
"password": "securepassword123",
"national_id": "123456789",
"gender": "male"
}'
Logging
The server implements structured logging with the following features:
- Request Logging - All HTTP requests are logged with timing
- Error Logging - Errors are logged with context
- Structured Fields - Logs include relevant metadata
- File Rotation - Logs are rotated based on size and age
Log Configuration
logging:
level: "info"
format: "json"
output: "file"
file:
path: "./logs/app.log"
max_size: 100
max_backups: 5
max_age: 30
compress: true
Security Features
CORS Configuration
middleware.CORSWithConfig(middleware.CORSConfig{
AllowOrigins: []string{"*"}, // Configure for production
AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete, http.MethodOptions},
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization},
})
Authentication (TODO)
- JWT token validation
- Role-based access control
- Token refresh mechanism
Error Handling
HTTP Status Codes
200- Success201- Created400- Bad Request401- Unauthorized404- Not Found409- Conflict422- Validation Error500- Internal Server Error
Response Format
{
"success": true,
"message": "Operation successful",
"data": {},
"meta": {}
}
Monitoring
Health Check
The /health endpoint provides basic server status:
- Server status
- Current timestamp
- Version information
Request Metrics
Each request is logged with:
- HTTP method
- Request path
- Response status
- Processing duration
- User agent
- Remote IP
Future Enhancements
- Authentication Middleware - Implement JWT validation
- Rate Limiting - Add request rate limiting
- Metrics - Add Prometheus metrics
- Tracing - Add distributed tracing
- API Documentation - Add Swagger/OpenAPI docs
- Testing - Add comprehensive test suite
Troubleshooting
Common Issues
-
MongoDB Connection Failed
- Ensure MongoDB is running
- Check connection URI in config
- Verify network connectivity
-
Port Already in Use
- Change port in config.yaml
- Kill existing process using the port
-
Permission Denied
- Ensure write permissions for log directory
- Check file permissions
Debug Mode
To enable debug logging, change the log level in config.yaml:
logging:
level: "debug"
Dependencies
Core Dependencies
github.com/labstack/echo/v4- HTTP frameworkgo.mongodb.org/mongo-driver- MongoDB drivergithub.com/google/uuid- UUID generationgolang.org/x/crypto/bcrypt- Password hashinggithub.com/asaskevich/govalidator- Input validation
Development Dependencies
github.com/stretchr/testify- Testing frameworkgo.uber.org/zap- Logging framework