go-api

command module
v1.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2025 License: MIT Imports: 6 Imported by: 0

README ΒΆ

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
  1. 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"]),
    }
}
  1. 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
  1. Define in interface:
// app/http/middleware/handler.go
type Middleware interface {
    CheckAppAuth() gin.HandlerFunc
    YourNewMiddleware() gin.HandlerFunc  // Add this
}
  1. 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
  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/new-feature
  3. Commit changes: git commit -am 'Add new feature'
  4. Push to branch: git push origin feature/new-feature
  5. 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.

Documentation ΒΆ

The Go Gopher

There is no documentation for this package.

Directories ΒΆ

Path Synopsis
app
config
Package config provides configuration management for the application.
Package config provides configuration management for the application.
http/controller/auth
Package auth provides authentication-related functionality for the application.
Package auth provides authentication-related functionality for the application.
http/middleware
Package middleware provides HTTP middleware functions for the application.
Package middleware provides HTTP middleware functions for the application.
http/router
Package router handles the routing for the application.
Package router handles the routing for the application.
job
Package job provides functionality for registering and managing scheduled jobs in the application.
Package job provides functionality for registering and managing scheduled jobs in the application.
job/monitor
Package monitor provides monitoring functionalities for various system aspects.
Package monitor provides monitoring functionalities for various system aspects.
model/auth
Package auth provides authentication and authorization functionalities.
Package auth provides authentication and authorization functionalities.
pkg/e
Package e defines error codes and messages used throughout the go-api project.
Package e defines error codes and messages used throughout the go-api project.
pkg/jwt
Package jwt provides functionality for generating and parsing JSON Web Tokens (JWT) specifically for application authentication in the go-api project.
Package jwt provides functionality for generating and parsing JSON Web Tokens (JWT) specifically for application authentication in the go-api project.
pkg/schedule
Package schedule provides functionality for scheduling and managing jobs in a distributed environment.
Package schedule provides functionality for scheduling and managing jobs in a distributed environment.
pkg/trace
Package trace provides functionality for generating unique trace identifiers.
Package trace provides functionality for generating unique trace identifiers.
worker
Package worker implements background task processing functionality.
Package worker implements background task processing functionality.
Package bootstrap provides functionality to initialize and start the application.
Package bootstrap provides functionality to initialize and start the application.
command
codegen command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL