Go-API Framework
Languages: English | δΈζ
Overview
go-api
is a powerful, high-performance Go framework designed for building enterprise-grade web APIs. It provides a complete solution with layered architecture, dependency injection, comprehensive middleware support, and automatic code generation capabilities.
Key Features
- π High Performance: Built on Gin framework with optimized logging and database connections
- ποΈ Layered Architecture: Strict Model β Repository β Service β Controller pattern
- π§ Dependency Injection: Clean architecture with proper separation of concerns
- βοΈ Configuration Management: Multi-environment support with JSON-based configuration
- π Advanced Logging: Structured logging with Zap for high performance
- ποΈ Multi-Database Support: MySQL (GORM) and MongoDB (qmgo) integration
- π JWT Authentication: Built-in app authentication with JWT tokens
- π Internationalization: Multi-language support (zh-CN, en-US)
- π Middleware System: CORS, authentication, request logging, and custom middleware
- β‘ Code Generation: Automatic model and repository generation from SQL files
- π Task Scheduling: Built-in job scheduling system
- π¨ Message Queue: Kafka producer/consumer support
- π¨ Monitoring: Panic recovery with notification integration
- π³ Docker Ready: Complete Docker support with optimized images
Quick Start
Method 1: Using Project Generator Script
# Download the project generator
curl -O https://raw.githubusercontent.com/seakee/go-api/main/scripts/generate.sh
chmod +x generate.sh
# Generate a new project
./generate.sh my-api-project v1.0.0
cd my-api-project
# Install dependencies and run
go mod tidy
make run
Method 2: Clone and Customize
# Clone the repository
git clone https://github.com/seakee/go-api.git
cd go-api
# Install dependencies
go mod download
# Copy and configure local settings
cp bin/configs/local.json.default bin/configs/local.json
# Edit bin/configs/local.json with your database settings
# Run the application
make run
Architecture Overview
go-api/
βββ app/ # Application layer
β βββ config/ # Configuration management
β β βββ config.go # Config loader and structures
β βββ http/ # HTTP layer
β β βββ controller/ # HTTP controllers
β β β βββ auth/ # Authentication controllers
β β β β βββ app.go # App CRUD operations
β β β β βββ handler.go # Auth handler interface
β β β β βββ jwt.go # JWT token operations
β β β βββ base.go # Base controller
β β βββ middleware/ # HTTP middleware
β β β βββ check_app_auth.go # JWT authentication
β β β βββ cors.go # CORS handling
β β β βββ handler.go # Middleware interface
β β β βββ request_logger.go # Request logging
β β β βββ set_trace_id.go # Trace ID injection
β β βββ router/ # Route definitions
β β β βββ external/ # External API routes
β β β β βββ service/ # External service routes
β β β β βββ auth/ # Auth endpoints
β β β βββ internal/ # Internal API routes
β β β β βββ service/ # Internal service routes
β β β β βββ auth/ # Auth endpoints
β β β βββ handler.go # Main router
β β βββ context.go # HTTP context wrapper
β βββ model/ # Data models
β β βββ auth/ # Authentication models
β β βββ app.go # App model (MySQL)
β β βββ app_mgo.go # App model (MongoDB)
β βββ pkg/ # Utility packages
β β βββ e/ # Error codes
β β β βββ code.go # Error code definitions
β β βββ jwt/ # JWT utilities
β β β βββ jwt.go # JWT generation/parsing
β β βββ schedule/ # Task scheduling
β β β βββ schedule.go # Job scheduler
β β βββ trace/ # Distributed tracing
β β βββ trace.go # Trace ID generation
β βββ repository/ # Data access layer
β β βββ auth/ # Auth repository
β β βββ app.go # App repository
β βββ service/ # Business logic layer
β β βββ auth/ # Auth services
β β βββ app.go # App service
β βββ worker/ # Background workers
β βββ handler.go # Worker handler
βββ bin/ # Runtime resources
β βββ configs/ # Configuration files
β β βββ dev.json # Development config
β β βββ local.json # Local config
β β βββ prod.json # Production config
β βββ data/ # Data files
β β βββ sql/ # SQL scripts
β β βββ auth_app.sql # App table schema
β βββ lang/ # Language files
β βββ en-US.json # English messages
β βββ zh-CN.json # Chinese messages
βββ bootstrap/ # Application bootstrap
β βββ app.go # Main app initialization
β βββ database.go # Database setup
β βββ http.go # HTTP server setup
β βββ kafka.go # Kafka setup
β βββ schedule.go # Scheduler setup
βββ command/ # CLI commands
β βββ codegen/ # Code generator
β βββ codegen/ # Generator logic
β βββ handler.go # CLI handler
β βββ README.md # Generator docs
βββ scripts/ # Utility scripts
β βββ generate.sh # Project generator
βββ docs/ # Project documentation
β βββ Home.md # Wiki homepage (English)
β βββ Home-zh.md # Wiki homepage (Chinese)
β βββ Architecture-Design.md # Architecture documentation
β βββ Development-Guide.md # Development workflow guide
β βββ API-Documentation.md # Complete API reference
β βββ Code-Generator-Guide.md # Code generation tool guide
β βββ Deployment-Guide.md # Production deployment guide
βββ Dockerfile # Docker configuration
βββ Makefile # Build automation
βββ docker-compose.yml # Docker Compose
βββ go.mod # Go module
βββ go.sum # Dependencies
βββ main.go # Application entry point
Core Components
1. Layered Architecture
The framework follows a strict 4-layer architecture:
- Model Layer: Data structures and database operations
- Repository Layer: Data access abstraction with interfaces
- Service Layer: Business logic implementation
- Controller Layer: HTTP request handling and response formatting
2. Configuration Management
Supports multiple environments with JSON-based configuration:
{
"system": {
"name": "go-api",
"run_mode": "debug",
"http_port": ":8080",
"jwt_secret": "your-secret-key"
},
"databases": [
{
"enable": true,
"db_type": "mysql",
"db_name": "go-api",
"db_host": "localhost:3306"
}
]
}
3. Middleware System
Built-in middleware for common functionality:
- Authentication: JWT-based app authentication
- CORS: Cross-origin resource sharing
- Logging: Structured request/response logging
- Trace ID: Distributed tracing support
- Panic Recovery: Automatic panic recovery with notifications
4. Authentication System
Complete JWT-based authentication:
# Get JWT token
curl -X POST http://localhost:8080/go-api/external/service/auth/token \
-d "app_id=your_app_id&app_secret=your_app_secret"
# Use token in requests
curl -H "Authorization: your_jwt_token" \
http://localhost:8080/go-api/external/service/auth/app
Development Guide
Adding a New Controller
- Create controller structure:
// app/http/controller/user/handler.go
package user
import (
"github.com/gin-gonic/gin"
"github.com/seakee/go-api/app/http"
)
type Handler interface {
Create() gin.HandlerFunc
GetByID() gin.HandlerFunc
}
type handler struct {
controller.BaseController
service userService.UserService
}
func NewHandler(appCtx *http.Context) Handler {
return &handler{
BaseController: controller.BaseController{
AppCtx: appCtx,
Logger: appCtx.Logger,
Redis: appCtx.Redis["go-api"],
I18n: appCtx.I18n,
},
service: userService.NewUserService(appCtx.MysqlDB["go-api"], appCtx.Redis["go-api"]),
}
}
- Register routes:
// app/http/router/external/service/user/user.go
func RegisterRoutes(api *gin.RouterGroup, ctx *http.Context) {
userHandler := user.NewHandler(ctx)
{
api.POST("user", ctx.Middleware.CheckAppAuth(), userHandler.Create())
api.GET("user/:id", userHandler.GetByID())
}
}
Adding Middleware
- Define in interface:
// app/http/middleware/handler.go
type Middleware interface {
CheckAppAuth() gin.HandlerFunc
YourNewMiddleware() gin.HandlerFunc // Add this
}
- Implement middleware:
// app/http/middleware/your_middleware.go
func (m middleware) YourNewMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Your middleware logic
c.Next()
}
}
Code Generation
Generate models and repositories from SQL files:
# Generate from SQL file
go run ./command/codegen/handler.go -name user_table
# Generate all SQL files
go run ./command/codegen/handler.go
# Custom paths
go run ./command/codegen/handler.go -sql custom/sql -model custom/model
SQL file format:
CREATE TABLE `users` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'Primary Key',
`username` varchar(50) NOT NULL COMMENT 'Username',
`email` varchar(100) NOT NULL COMMENT 'Email Address',
`status` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Status',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='User Information';
API Endpoints
External APIs (Public)
Method |
Endpoint |
Description |
Auth Required |
POST |
/go-api/external/service/auth/token |
Get JWT token |
No |
POST |
/go-api/external/service/auth/app |
Create app |
Yes |
GET |
/go-api/external/service/ping |
Health check |
No |
Internal APIs (Private)
Method |
Endpoint |
Description |
Auth Required |
POST |
/go-api/internal/service/auth/token |
Get JWT token |
No |
POST |
/go-api/internal/service/auth/app |
Create app |
Yes |
GET |
/go-api/internal/service/ping |
Health check |
No |
Docker Deployment
Using Docker Compose
# docker-compose.yml
version: '3.8'
services:
go-api:
build: .
ports:
- "8080:8080"
volumes:
- ./bin/configs:/bin/configs
- ./bin/logs:/bin/logs
environment:
- RUN_ENV=prod
- APP_NAME=go-api
depends_on:
- mysql
- redis
mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: go-api
ports:
- "3306:3306"
redis:
image: redis:7-alpine
ports:
- "6379:6379"
Build and Run
# Build Docker image
make docker-build
# Run with Docker Compose
docker-compose up -d
# Run single container
make docker-run
Build Commands
# Development
make run # Run application
make test # Run tests
make fmt # Format code
make all # fmt + test + build
# Production
make build # Build binary
make docker-build # Build Docker image
make docker-run # Run Docker container
Environment Variables
Variable |
Description |
Default |
RUN_ENV |
Runtime environment |
local |
APP_NAME |
Application name |
go-api |
CONFIG_DIR |
Configuration directory |
./bin/configs |
Documentation
Complete project documentation is available in the docs/
directory:
Contributing
- Fork the repository
- Create a feature branch:
git checkout -b feature/new-feature
- Commit changes:
git commit -am 'Add new feature'
- Push to branch:
git push origin feature/new-feature
- Submit a Pull Request
See Contributing Guide for more details.
License
This project is licensed under the MIT License - see the LICENSE file for details.