Skip to content

tranvuongduy2003/go-mvc

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

31 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Go MVC - Enterprise Grade Go Web Application

Go Version License Docker Clean Code CI/CD AI Powered

A modern, production-ready Go web application built with Clean Architecture, Domain-Driven Design (DDD), and Enterprise patterns. Features comprehensive observability, AI-powered development, automated CI/CD, and self-documenting code standards.

πŸš€ Features

πŸ€– AI-Powered Development

  • AI Code Generation: Auto-generate complete APIs from User Stories
  • Self-Documenting Code: Minimal comments, maximum clarity through naming
  • AI Coding Standards: Comprehensive rules for consistent, clean code
  • Production-Ready Output: Generated code includes validation, error handling, tests
  • Architecture Compliance: AI follows Clean Architecture patterns automatically

Core Features

  • Clean Architecture: Clear separation of Domain, Application, Infrastructure, Presentation layers
  • Domain-Driven Design: Rich domain models with business logic encapsulation
  • Dependency Injection: Uber FX for modular dependency management
  • CQRS Pattern: Command Query Responsibility Segregation
  • Repository Pattern: Abstract data access layer
  • Self-Documenting Code: Clear naming eliminates need for comments

Infrastructure

  • HTTP Framework: Gin with custom middleware stack
  • Database: PostgreSQL with GORM ORM
  • Cache: Redis for high-performance caching
  • Message Queue: RabbitMQ for async processing
  • Authentication: JWT-based with security middleware
  • Email Service: SMTP integration with MailCatcher for development testing

Observability Stack

  • Metrics: Prometheus + Grafana dashboards
  • Distributed Tracing: Jaeger with OpenTelemetry
  • Logging: Structured logging with Zap
  • Health Checks: Comprehensive health monitoring
  • Performance Profiling: pprof integration

Development Tools

  • Hot Reload: Air for development
  • Code Quality: golangci-lint, gosec, gofumpt
  • Testing: Unit, integration, and benchmark tests
  • Documentation: Swagger/OpenAPI generation
  • Database Migrations: golang-migrate/migrate v4.19.0+ with timestamp-based versioning
  • MCP Agents: AI-powered API testing, database management, and GitHub automation agents

πŸ€– MCP Agents (Model Context Protocol)

  • API Testing Agent: 6 tools for REST API testing (GET, POST, PUT, PATCH, DELETE, TEST)
  • Database Agent: 6 tools for PostgreSQL management (connect, query, schema, migrate, analyze, generate SQL)
  • GitHub Agent: 10 tools for GitHub automation (repo info, issues, PRs, workflows, code search, branches)
  • Modular Architecture: Scalable, maintainable TypeScript implementation
  • Full Documentation: Architecture, quick reference, and user guides included
  • Integration Ready: Works with Claude Desktop and other MCP clients

πŸ“ Project Structure

go-mvc/
β”œβ”€β”€ cmd/                        # Application entry points
β”‚   β”œβ”€β”€ main.go                # Main server application
β”‚   β”œβ”€β”€ cli/                   # Command-line interface
β”‚   β”œβ”€β”€ worker/                # Background worker
β”‚   └── migrate/               # Database migration tool
β”œβ”€β”€ internal/                   # Private application code
β”‚   β”œβ”€β”€ domain/                # Domain Layer - Business logic & entities
β”‚   β”‚   β”œβ”€β”€ auth/             # Authentication domain
β”‚   β”‚   β”œβ”€β”€ user/             # User domain
β”‚   β”‚   β”œβ”€β”€ job/              # Background job domain
β”‚   β”‚   β”œβ”€β”€ messaging/        # Messaging domain
β”‚   β”‚   └── shared/           # Shared domain objects
β”‚   β”œβ”€β”€ application/           # Application Layer - Use cases
β”‚   β”‚   β”œβ”€β”€ commands/         # Write operations (CQRS)
β”‚   β”‚   β”œβ”€β”€ queries/          # Read operations (CQRS)
β”‚   β”‚   β”œβ”€β”€ dto/              # Data transfer objects
β”‚   β”‚   β”œβ”€β”€ services/         # Application services
β”‚   β”‚   β”œβ”€β”€ validators/       # Input validation
β”‚   β”‚   └── event_handlers/   # Domain event handlers
β”‚   β”œβ”€β”€ infrastructure/        # Infrastructure Layer - Technical details
β”‚   β”‚   β”œβ”€β”€ cache/            # Cache implementations (Redis)
β”‚   β”‚   β”œβ”€β”€ database/         # Database setup
β”‚   β”‚   β”œβ”€β”€ persistence/      # Repository implementations
β”‚   β”‚   β”œβ”€β”€ messaging/        # Message queue (NATS)
β”‚   β”‚   β”œβ”€β”€ jobs/             # Background job system
β”‚   β”‚   β”œβ”€β”€ security/         # Security utilities
β”‚   β”‚   β”œβ”€β”€ tracing/          # Distributed tracing
β”‚   β”‚   └── metrics/          # Prometheus metrics
β”‚   β”œβ”€β”€ presentation/          # Presentation Layer - HTTP handlers
β”‚   β”‚   └── http/             # HTTP transport
β”‚   β”‚       β”œβ”€β”€ handlers/     # Request handlers
β”‚   β”‚       └── middleware/   # HTTP middleware
β”‚   └── modules/               # Dependency injection modules
β”œβ”€β”€ pkg/                       # Public reusable packages
β”‚   β”œβ”€β”€ errors/               # Error utilities
β”‚   β”œβ”€β”€ jwt/                  # JWT utilities
β”‚   β”œβ”€β”€ pagination/           # Pagination helpers
β”‚   β”œβ”€β”€ response/             # Response formatting
β”‚   └── validator/            # Validation utilities
β”œβ”€β”€ configs/                   # Configuration files
β”‚   β”œβ”€β”€ development.yaml      # Development config
β”‚   β”œβ”€β”€ production.yaml       # Production config
β”‚   └── grafana/              # Grafana dashboards
β”œβ”€β”€ docs/                      # Complete documentation (ebook format)
β”‚   β”œβ”€β”€ BOOK.md               # Main table of contents
β”‚   β”œβ”€β”€ INDEX.md              # Quick access index
β”‚   β”œβ”€β”€ README.md             # Documentation overview
β”‚   └── book/                 # Organized chapters
β”‚       β”œβ”€β”€ 01-getting-started/
β”‚       β”œβ”€β”€ 02-architecture/
β”‚       β”œβ”€β”€ 03-development-guide/
β”‚       β”œβ”€β”€ 04-features/
β”‚       β”œβ”€β”€ 05-ai-development/
β”‚       β”œβ”€β”€ 06-operations/
β”‚       └── appendix/
└── scripts/                   # Build and deployment scripts

πŸ“– See Project Structure Guide for detailed explanations

πŸ› οΈ Quick Start

Prerequisites

  • Go 1.24.5+
  • Docker & Docker Compose
  • Make (for build automation)

1. Clone and Setup

git clone https://github.com/tranvuongduy2003/go-mvc.git
cd go-mvc

# Setup development environment
make setup

2. Start Development Services

# Start database and cache
make docker-up-db

# Start monitoring stack
make monitoring

3. Run Application

# Development with hot reload
make dev

# Or run without hot reload
make run

4. Setup MCP Agents (Optional)

# Setup and build MCP agents
make mcp-all

# Test MCP agents
make mcp-test

# View MCP configuration
make mcp-config-show

# Check status
make mcp-status

πŸ“– See MCP Agents Documentation for detailed usage

Or run directly

make run


### 4. Access Services
- **Application**: http://localhost:8080
- **Health Check**: http://localhost:8080/health
- **Metrics**: http://localhost:8080/metrics
- **MailCatcher**: http://localhost:1080 (email testing interface)
- **Prometheus**: http://localhost:9091
- **Grafana**: http://localhost:3000 (admin/admin)
- **Jaeger**: http://localhost:16686

## πŸš€ DevOps & CI/CD

### Automated CI/CD Pipeline

Complete DevOps automation vα»›i GitHub Actions vΓ  AI Assistant:

**6 Workflows Tα»± Δ‘α»™ng**:
- βœ… **CI Pipeline**: Build, test, lint vα»›i PostgreSQL/Redis/NATS
- βœ… **Security**: Gosec, Trivy, CodeQL, secret scanning
- βœ… **Docker**: Multi-platform builds, GHCR publishing
- βœ… **Release**: Automated releases, binaries, deployment
- βœ… **Dependencies**: Auto-update Go modules, Actions, Docker
- βœ… **AI Assistant**: AI code review, docs, coverage analysis

**AI Development Scripts**:
```bash
# AI code review
./.github/scripts/ai-code-review.sh

# Generate CRUD code
./.github/scripts/ai-code-generator.sh Product full

# Analyze workflow
./.github/scripts/ai-workflow-optimizer.sh

AI Bot Commands (trong PR comments):

/ai review      # Trigger AI code review
/ai optimize    # Analyze workflow  
/ai docs        # Generate documentation
/ai help        # Show available commands

Quick Start:

# 1. Push code triggers CI/CD automatically
git push origin master

# 2. Create PR vα»›i AI assistance
gh pr create
# Comment: /ai review

# 3. Release vα»›i tag
git tag -a v1.0.0 -m "Release v1.0.0"
git push origin v1.0.0
# Auto: build binaries, create release, deploy

πŸ“– Complete DevOps Guide:

πŸ—οΈ Architecture Overview

This application follows Clean Architecture principles with clear separation of concerns:

1. Domain Layer (internal/domain/)

  • Entities: Core business objects with rich behavior
  • Value Objects: Immutable data structures
  • Domain Events: Business event definitions
  • Repository Interfaces: Data access contracts
  • Domain Services: Complex business logic

2. Application Layer (internal/application/)

  • Commands: Write operations (CQRS)
  • Queries: Read operations (CQRS)
  • Application Services: Use case orchestration
  • DTOs: Data transfer objects
  • Validators: Input validation logic
  • Event Handlers: Domain event processing

3. Infrastructure Layer (internal/infrastructure/)

  • Persistence: Database repository implementations
  • Cache: Redis caching layer
  • Messaging: NATS message broker
  • Jobs: Background job processing
  • Security: Authentication & authorization
  • Tracing: OpenTelemetry integration
  • Metrics: Prometheus metrics

4. Presentation Layer (internal/presentation/)

  • HTTP Handlers: REST API endpoints
  • Middleware: Cross-cutting concerns (auth, logging, tracing)
  • Response Formatting: Consistent API responses

5. Modules (internal/modules/)

  • Dependency Injection: Uber FX modules for each domain
  • Lifecycle Management: Startup/shutdown coordination

πŸ“– See AGENT.md for comprehensive architecture guide and AI assistant instructions

πŸ€– AI-Powered API Generation

This project includes comprehensive AI assistance for development. The AGENT.md file contains complete instructions for AI assistants working on this codebase.

Quick AI Generation

AI will auto-generate complete, production-ready code following Clean Architecture:

  • βœ… Domain Layer: Entities, value objects, repository interfaces
  • βœ… Application Layer: Commands/queries, DTOs, validators, services
  • βœ… Infrastructure Layer: Repository implementations, migrations
  • βœ… Presentation Layer: HTTP handlers, routes, middleware
  • βœ… Integration: Complete dependency injection setup
  • βœ… Self-Documenting Code: Clear names, minimal comments

AI Documentation & Standards

Code Quality Principles

Self-Documenting Code - Code should be clear through naming, not comments:

// ❌ BAD - Unnecessary comments
// CreateUser creates a new user
func CreateUser(email, password string) (*User, error) {
    // Validate email
    if !isValid(email) {
        return nil, errors.New("invalid")
    }
    ...
}

// βœ… GOOD - Clear naming, no comments needed
func CreateUser(email, password string) (*User, error) {
    if err := ValidateEmail(email); err != nil {
        return nil, err
    }
    ...
}

πŸ“– See AI Coding Standards for complete self-documenting code guide

πŸ”§ Development Commands

Build & Run

make build          # Build server binary
make build-all      # Build all binaries
make run           # Run server
make dev           # Run with hot reload

AI-Generated Code

make validate-generated [entity]  # Validate AI-generated code
make test-generated [entity]      # Test generated components
make integrate-generated [entity] # Integrate with existing codebase

Testing

make test                # Run all tests
make test-unit          # Run unit tests
make test-integration   # Run integration tests
make test-coverage      # Run with coverage report
make benchmark          # Run benchmarks

Code Quality

make lint          # Run linter
make format        # Format code
make vet           # Run go vet
make security      # Security scan

Database

# Migration management (golang-migrate/migrate v4.19.0+)
make migrate-up      # Apply all pending migrations
make migrate-down    # Rollback last migration
make migrate-create  # Create new timestamped migration
make migrate-status  # Show migration status
make migrate-version # Show current version

Docker

make docker-up           # Start all services
make docker-up-db        # Start database only
make docker-up-monitoring # Start monitoring stack
make docker-down         # Stop services

MCP Agents

make mcp-setup       # Install MCP dependencies
make mcp-build       # Build MCP agents
make mcp-test        # Run MCP tests
make mcp-all         # Setup, build, and test
make mcp-status      # Check MCP status
make mcp-docs        # View MCP documentation
make mcp-config-show # Show configuration example
make mcp-dev         # Watch mode (rebuild on changes)
make mcp-clean       # Clean MCP artifacts
make mcp-rebuild     # Clean rebuild

πŸ“– MCP Agent Documentation:

Monitoring

make monitoring      # Start monitoring with URLs
make metrics        # View metrics
make health         # Health check
make trace-test     # Generate test traces

πŸ“Š Monitoring & Observability

Metrics (Prometheus + Grafana)

  • HTTP Metrics: Request duration, status codes, throughput
  • System Metrics: CPU, memory, goroutines
  • Database Metrics: Connection pool, query performance
  • Cache Metrics: Hit/miss ratios, operation latency

Distributed Tracing (Jaeger)

  • Request Tracing: End-to-end request flow
  • Database Queries: Query execution traces
  • External Calls: Third-party service calls
  • Error Tracking: Exception and error traces

Logging (Zap)

  • Structured Logging: JSON formatted logs
  • Log Levels: Debug, Info, Warn, Error
  • Request Logging: HTTP request/response logs
  • Error Logging: Detailed error information

πŸš€ Deployment

Docker Deployment

# Build Docker image
make docker-build

# Start production stack
docker-compose up -d

Environment Configuration

  • Development: configs/development.yaml
  • Production: configs/production.yaml

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow Clean Architecture principles
  • Use self-documenting code (see AI Coding Standards)
  • Write comprehensive tests
  • Add proper documentation to AGENT.md or README.md
  • Use conventional commits
  • Ensure code quality with linters
  • NO unnecessary comments - code should be clear through naming
  • DO NOT create summary markdown files after implementing features

πŸ“š Documentation

Core Documentation

MCP Agents

πŸ›‘οΈ Security

  • JWT Authentication: Secure token-based auth
  • CORS Protection: Cross-origin resource sharing
  • Rate Limiting: Request throttling
  • Security Headers: XSS, CSRF protection
  • Input Validation: Comprehensive request validation
  • SQL Injection Prevention: Parameterized queries

πŸ“ˆ Performance

  • Connection Pooling: Database connection optimization
  • Caching Strategy: Redis-based caching
  • Goroutine Management: Efficient concurrent processing
  • Memory Management: Optimized memory usage
  • Profiling: Built-in performance profiling

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™‹β€β™‚οΈ Support

For questions, issues, or contributions:

Quick Documentation Links


⭐ Star this repository if you find it helpful!

Built with ❀️ using Clean Architecture, DDD, and Self-Documenting Code principles

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published