fork

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 5, 2025 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Fork HTTP Framework

Fork HTTP Framework Go Version License Build Status

Framework HTTP linh hoạt và hiệu năng cao cho Go với kiến trúc adapter pattern

📚 Tài liệu • 🚀 Bắt đầu nhanh • 📖 Hướng dẫn • 🔧 Cấu hình


🌟 Tổng quan

Fork HTTP Framework là một framework HTTP enterprise-grade được thiết kế cho các ứng dụng Go production. Framework cung cấp kiến trúc adapter pattern linh hoạt, hỗ trợ multiple HTTP engines và tối ưu hiệu năng với trie-based routing và zero-allocation patterns.

✨ Điểm nổi bật
  • 🏗️ Adapter Pattern: Hỗ trợ multiple HTTP engines (net/http, fasthttp, http2, quic)
  • 🚄 High Performance: Zero-allocation routing với trie structure optimization
  • 🛡️ Production Ready: Graceful shutdown, error handling và monitoring tích hợp
  • ⚙️ YAML Configuration: Auto-loading middleware và configuration management
  • 🔗 Dependency Injection: Service container tích hợp với lifecycle management
  • 🎯 Context System: Powerful context với data binding và validation
  • 🔀 Flexible Routing: Route groups, parameters, wildcards và middleware chains
  • 📦 30+ Middleware: Auto-configured middleware ecosystem với YAML

📦 Cài đặt

# Framework core
go get go.fork.vn/fork

# Các adapters
go get github.com/Fork/adapter/fasthttp    # FastHTTP adapter
go get github.com/Fork/adapter/http2       # HTTP/2 support  
go get github.com/Fork/adapter/quic        # HTTP/3 QUIC support

🚀 Bắt đầu nhanh

Ứng dụng cơ bản
package main

import (
    "go.fork.vn/fork"
)

func main() {
    // Tạo WebApp instance
    app := fork.New()
    
    // Định nghĩa basic routes
    app.Get("/", func(c fork.Context) error {
        return c.String(200, "Hello, Fork HTTP Framework!")
    })
    
    app.Get("/health", func(c fork.Context) error {
        return c.JSON(200, map[string]interface{}{
            "status": "ok",
            "framework": "Fork HTTP",
        })
    })
    
    // Route với parameters
    app.Get("/user/:id", func(c fork.Context) error {
        userID := c.Param("id")
        return c.JSON(200, map[string]string{
            "user_id": userID,
            "message": "User profile",
        })
    })
    
    // Khởi động server
    app.Listen(":3000")
}
Ứng dụng với Configuration
package main

import (
    "log"
    "go.fork.vn/fork"
    "go.fork.vn/fork/adapter"
)

func main() {
    // Load configuration từ YAML
    config, err := fork.LoadConfigFromFile("configs/app.yaml")
    if err != nil {
        log.Fatal("Failed to load config:", err)
    }
    
    // Tạo application với config
    app := fork.NewWithConfig(config)
    
    // Sử dụng FastHTTP adapter cho high performance
    fastAdapter := adapter.NewFastHTTPAdapter()
    app.SetAdapter(fastAdapter)
    
    // API routes group
    api := app.Group("/api/v1")
    {
        api.Get("/health", healthHandler)
        api.Post("/users", createUserHandler)
        api.Get("/users/:id", getUserHandler)
        api.Put("/users/:id", updateUserHandler)
    }
    
    // Khởi động với graceful shutdown
    app.ListenWithGracefulShutdown(":8080")
}
Configuration YAML
# configs/app.yaml
graceful_shutdown:
  enabled: true
  timeout: 30
  wait_for_connections: true
  signal_buffer_size: 1

http:
  middleware:
    # Core middleware
    recover:
      enabled: true
    logger:
      enabled: true
      format: "json"
    cors:
      enabled: true
      allow_origins: ["*"]
    
    # Performance middleware  
    compression:
      enabled: true
      level: 6
    cache:
      enabled: true
      ttl: 300

🏗️ Kiến trúc Framework

graph TB
    subgraph "Fork HTTP Framework Architecture"
        A[WebApp] --> B[Router System]
        A --> C[Middleware Chain]
        A --> D[Service Container]
        
        B --> E[Trie-based Routing]
        B --> F[Route Groups]
        B --> G[Route Matching]
        
        C --> H[Auto-configured Middleware]
        C --> I[30+ Middleware Packages]
        
        D --> J[Dependency Injection]
        D --> K[Service Lifecycle]
        
        A --> L[Context System]
        L --> M[Request/Response Processing]
        L --> N[Data Binding & Validation]
        
        A --> O[Adapter Layer]
        O --> P[net/http]
        O --> Q[FastHTTP]
        O --> R[HTTP/2]
        O --> S[QUIC/HTTP3]
    end
    
    style A fill:#e1f5fe
    style O fill:#f3e5f5
    style B fill:#e8f5e8
    style C fill:#fff3e0
Core Components Flow
sequenceDiagram
    participant Client
    participant Adapter
    participant Router
    participant Middleware
    participant Handler
    participant Context
    
    Client->>Adapter: HTTP Request
    Adapter->>Router: Process Route
    Router->>Middleware: Apply Chain
    Middleware->>Handler: Execute Handler
    Handler->>Context: Access Request/Response
    Context-->>Handler: Processed Data
    Handler-->>Middleware: Response
    Middleware-->>Router: Response
    Router-->>Adapter: Final Response
    Adapter-->>Client: HTTP Response

🎯 Context System

Request Processing & Data Binding
type User struct {
    ID    int    `json:"id" validate:"required"`
    Name  string `json:"name" validate:"required,min=2,max=50"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"min=18,max=120"`
}

func createUserHandler(c fork.Context) error {
    var user User
    
    // Parse JSON request body
    if err := c.BodyParser(&user); err != nil {
        return c.Status(400).JSON(map[string]interface{}{
            "error": "Invalid JSON format",
            "details": err.Error(),
        })
    }
    
    // Validate struct data với tags
    if err := c.Validate(&user); err != nil {
        return c.Status(422).JSON(map[string]interface{}{
            "error": "Validation failed",
            "details": err.Error(),
        })
    }
    
    // Access route parameters
    userID := c.Param("id")
    
    // Access query parameters với default values
    page := c.QueryInt("page", 1)
    limit := c.QueryInt("limit", 10)
    filter := c.Query("filter", "active")
    
    // Set response headers
    c.Set("X-User-ID", userID)
    c.Set("X-Request-ID", c.Get("request_id"))
    
    // Return JSON response
    return c.Status(201).JSON(map[string]interface{}{
        "user": user,
        "meta": map[string]interface{}{
            "page": page,
            "limit": limit,
            "filter": filter,
        },
    })
}

🚦 Router System

Advanced Routing Features
app := fork.New()

// Basic HTTP methods
app.Get("/", homeHandler)
app.Post("/users", createUserHandler)
app.Put("/users/:id", updateUserHandler)
app.Delete("/users/:id", deleteUserHandler)
app.Patch("/users/:id", patchUserHandler)

// Route parameters với patterns
app.Get("/users/:id", getUserHandler)                    // Named parameter
app.Get("/users/:id/posts/:postId", getPostHandler)     // Multiple parameters
app.Get("/files/*filepath", fileHandler)                // Wildcard parameter

// Optional parameters
app.Get("/search/:query?", searchHandler)               // Optional query

// Regex constraints (nếu supported)
app.Get("/users/:id([0-9]+)", getUserByIDHandler)       // Numeric ID only

// Route groups với middleware
api := app.Group("/api/v1")
{
    // Public endpoints
    api.Get("/health", healthHandler)
    api.Post("/auth/login", loginHandler)
    
    // Protected endpoints group
    protected := api.Group("/", authMiddleware)
    {
        protected.Get("/profile", getProfileHandler)
        protected.Put("/profile", updateProfileHandler)
        
        // Admin endpoints
        admin := protected.Group("/admin", adminMiddleware)
        {
            admin.Get("/users", listUsersHandler)
            admin.Delete("/users/:id", deleteUserHandler)
            admin.Get("/stats", getStatsHandler)
        }
    }
}

// Static file serving
app.Static("/static", "./public")
app.Static("/uploads", "./uploads")
Route Performance với Trie
// Framework sử dụng trie structure cho fast route matching
// Zero-allocation patterns cho high-performance routing
// O(log n) lookup time với memory optimization

🛠️ Middleware System

Auto-configured Middleware

Framework hỗ trợ 30+ middleware packages được auto-load thông qua YAML configuration:

# configs/app.yaml
http:
  middleware:
    # Security middleware
    recover:
      enabled: true
    helmet:
      enabled: true
      hsts: true
      xss_protection: true
    cors:
      enabled: true
      allow_origins: ["https://example.com"]
      allow_methods: ["GET", "POST", "PUT", "DELETE"]
      
    # Monitoring & Logging
    logger:
      enabled: true
      format: "json"
      level: "info"
    monitor:
      enabled: true
      metrics_path: "/metrics"
      
    # Performance
    compression:
      enabled: true
      level: 6
      types: ["text/html", "application/json"]
    cache:
      enabled: true
      ttl: 300
      memory_limit: "100MB"
      
    # Rate limiting
    rate_limit:
      enabled: true
      max_requests: 100
      window: "1m"
      
    # Authentication
    jwt:
      enabled: true
      secret: "${JWT_SECRET}"
      expire: "24h"
Custom Middleware
// Custom middleware function
func customAuthMiddleware(c fork.Context) error {
    token := c.Get("Authorization")
    if token == "" {
        return c.Status(401).JSON(map[string]string{
            "error": "Missing authorization token",
        })
    }
    
    // Validate token logic...
    // Set user context...
    
    return c.Next() // Continue to next middleware/handler
}

// Apply middleware
app.Use(customAuthMiddleware)

// Route-specific middleware
app.Get("/protected", authMiddleware, protectedHandler)

🔧 Cấu hình Framework

WebApp Configuration Structure
type WebAppConfig struct {
    GracefulShutdown GracefulShutdownConfig `yaml:"graceful_shutdown"`
}

type GracefulShutdownConfig struct {
    Enabled            bool `yaml:"enabled"`
    Timeout            int  `yaml:"timeout"`
    WaitForConnections bool `yaml:"wait_for_connections"`
    SignalBufferSize   int  `yaml:"signal_buffer_size"`
    
    // Callback functions
    OnShutdownStart    func()
    OnShutdownComplete func()
    OnShutdownError    func(error)
}
Production Configuration
# configs/production.yaml
graceful_shutdown:
  enabled: true
  timeout: 30
  wait_for_connections: true
  signal_buffer_size: 1

server:
  host: "0.0.0.0"
  port: 8080
  read_timeout: "30s"
  write_timeout: "30s"
  idle_timeout: "120s"

adapter:
  type: "fasthttp"
  config:
    max_request_body_size: 4194304
    concurrency: 1000
    reduce_memory_usage: true

http:
  middleware:
    recover:
      enabled: true
    logger:
      enabled: true
      format: "json"
      level: "info"
    compression:
      enabled: true
      level: 6
    security_headers:
      enabled: true

🔌 Dependency Injection

Service Container Integration
import "go.fork.vn/di"

// Define services
type UserService struct {
    db Database
}

type EmailService struct {
    apiKey string
}

func main() {
    // Create DI container
    container := di.New()
    
    // Register services
    container.Register(&UserService{db: NewDatabase()})
    container.Register(&EmailService{apiKey: "your-api-key"})
    
    // Create app với DI container
    app := fork.NewWithContainer(container)
    
    app.Post("/users", createUserWithDI)
    
    app.Listen(":8080")
}

func createUserWithDI(c fork.Context) error {
    // Resolve services từ container
    userService := di.Resolve[*UserService](c.Container())
    emailService := di.Resolve[*EmailService](c.Container())
    
    var user User
    if err := c.BodyParser(&user); err != nil {
        return c.Status(400).JSON(map[string]string{
            "error": "Invalid request",
        })
    }
    
    // Use services
    createdUser, err := userService.Create(user)
    if err != nil {
        return c.Status(500).JSON(map[string]string{
            "error": "Failed to create user",
        })
    }
    
    // Send welcome email
    go emailService.SendWelcomeEmail(createdUser.Email)
    
    return c.Status(201).JSON(createdUser)
}

🚀 Adapter Pattern

Multiple HTTP Engine Support
import (
    "go.fork.vn/fork"
    "go.fork.vn/fork/adapter"
)

func main() {
    app := fork.New()
    
    // Sử dụng different adapters cho different use cases
    
    // 1. Standard net/http (default)
    // app.SetAdapter(adapter.NewNetHTTPAdapter())
    
    // 2. FastHTTP cho high performance
    fastAdapter := adapter.NewFastHTTPAdapter()
    app.SetAdapter(fastAdapter)
    
    // 3. HTTP/2 support
    // http2Adapter := adapter.NewHTTP2Adapter()
    // app.SetAdapter(http2Adapter)
    
    // 4. QUIC/HTTP3 support
    // quicAdapter := adapter.NewQUICAdapter()
    // app.SetAdapter(quicAdapter)
    
    app.Get("/", func(c fork.Context) error {
        return c.String(200, "Hello from " + c.Adapter().Name())
    })
    
    app.Listen(":8080")
}
Adapter Configuration
// FastHTTP adapter với custom config
fastAdapter := adapter.NewFastHTTPAdapter()
fastAdapter.Configure(adapter.FastHTTPConfig{
    MaxRequestBodySize: 4 * 1024 * 1024, // 4MB
    Concurrency:        1000,
    ReduceMemoryUsage:  true,
    ReadTimeout:        30 * time.Second,
    WriteTimeout:       30 * time.Second,
})

app.SetAdapter(fastAdapter)

📊 Performance Benchmarks

Framework được tối ưu cho high-performance với zero-allocation patterns:

Benchmark Results (Go 1.23, amd64):
=====================================================
BenchmarkRouter-8               5,000,000   240 ns/op     0 allocs/op
BenchmarkContext-8              3,000,000   450 ns/op     1 allocs/op  
BenchmarkMiddleware-8           2,000,000   680 ns/op     2 allocs/op
BenchmarkJSONBinding-8          1,000,000   1,200 ns/op   3 allocs/op
BenchmarkTrieRouting-8          10,000,000  120 ns/op     0 allocs/op

Memory Usage:
=====================================================
Base memory footprint:         ~8MB
Per request allocation:        ~512 bytes
Router memory usage:           ~2MB (for 10K routes)
Middleware overhead:           ~64 bytes per middleware
Performance Features
  • Zero-allocation routing với trie structure
  • Memory pooling cho reusable objects
  • Efficient middleware chain với minimal overhead
  • Adapter-based engine selection cho performance tuning
  • Context reuse để giảm GC pressure

🧪 Testing Framework

Testing Utilities
package main

import (
    "testing"
    "net/http/httptest"
    "strings"
    "github.com/stretchr/testify/assert"
    "go.fork.vn/fork"
)

func TestUserAPI(t *testing.T) {
    // Setup test app
    app := fork.New()
    app.Post("/users", createUserHandler)
    
    // Test successful creation
    t.Run("Create user successfully", func(t *testing.T) {
        jsonBody := `{"name":"John Doe","email":"john@example.com","age":25}`
        req := httptest.NewRequest("POST", "/users", strings.NewReader(jsonBody))
        req.Header.Set("Content-Type", "application/json")
        
        resp, err := app.Test(req)
        assert.NoError(t, err)
        assert.Equal(t, 201, resp.StatusCode)
    })
    
    // Test validation error
    t.Run("Validation error", func(t *testing.T) {
        jsonBody := `{"name":"","email":"invalid-email"}`
        req := httptest.NewRequest("POST", "/users", strings.NewReader(jsonBody))
        req.Header.Set("Content-Type", "application/json")
        
        resp, err := app.Test(req)
        assert.NoError(t, err)
        assert.Equal(t, 422, resp.StatusCode)
    })
}

func TestMiddleware(t *testing.T) {
    app := fork.New()
    
    // Add test middleware
    app.Use(func(c fork.Context) error {
        c.Set("test-header", "test-value")
        return c.Next()
    })
    
    app.Get("/test", func(c fork.Context) error {
        value := c.Get("test-header")
        return c.String(200, value)
    })
    
    req := httptest.NewRequest("GET", "/test", nil)
    resp, err := app.Test(req)
    
    assert.NoError(t, err)
    assert.Equal(t, 200, resp.StatusCode)
}

🚀 Production Deployment

Docker Deployment
# Dockerfile
FROM golang:1.23-alpine AS builder

WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download

COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .

FROM alpine:latest
RUN apk --no-cache add ca-certificates tzdata
WORKDIR /root/

COPY --from=builder /app/main .
COPY --from=builder /app/configs ./configs

EXPOSE 8080
CMD ["./main"]
Docker Compose
# docker-compose.yml
version: '3.8'

services:
  fork-app:
    build: .
    ports:
      - "8080:8080"
    environment:
      - ENV=production
      - DATABASE_URL=${DATABASE_URL}
      - REDIS_URL=${REDIS_URL}
    volumes:
      - ./configs:/root/configs:ro
      - ./logs:/root/logs
    restart: unless-stopped
    
  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"
    restart: unless-stopped
    
  postgres:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: fork_app
      POSTGRES_USER: ${DB_USER}
      POSTGRES_PASSWORD: ${DB_PASSWORD}
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
    restart: unless-stopped

volumes:
  postgres_data:
Graceful Shutdown
package main

import (
    "context"
    "log"
    "os"
    "os/signal"
    "syscall"
    "time"
    "go.fork.vn/fork"
)

func main() {
    app := fork.New()
    
    // Configure graceful shutdown với callbacks
    app.ConfigureGracefulShutdown(fork.GracefulShutdownConfig{
        Enabled:            true,
        Timeout:            30 * time.Second,
        WaitForConnections: true,
        SignalBufferSize:   1,
        
        OnShutdownStart: func() {
            log.Println("Starting graceful shutdown...")
        },
        OnShutdownComplete: func() {
            log.Println("Graceful shutdown completed")
        },
        OnShutdownError: func(err error) {
            log.Printf("Shutdown error: %v", err)
        },
    })
    
    // Setup routes
    app.Get("/health", func(c fork.Context) error {
        return c.JSON(200, map[string]string{"status": "ok"})
    })
    
    // Start với graceful shutdown
    go func() {
        if err := app.Listen(":8080"); err != nil {
            log.Printf("Server error: %v", err)
        }
    }()
    
    // Wait for shutdown signal
    quit := make(chan os.Signal, 1)
    signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
    <-quit
    
    log.Println("Received shutdown signal")
    
    // Graceful shutdown với timeout
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()
    
    if err := app.Shutdown(ctx); err != nil {
        log.Printf("Forced shutdown: %v", err)
    }
}

📚 Tài liệu chi tiết

🏗️ Core Architecture
Tài liệu Mô tả Trạng thái
Configuration Hệ thống cấu hình YAML và WebAppConfig ✅ Updated
Service Provider DI container và service lifecycle ✅ Available
Web Application Core WebApp object và application lifecycle ✅ Available
🎯 Request Processing
Tài liệu Mô tả Trạng thái
Context, Request & Response HTTP context system và data processing ✅ Available
Router Trie-based routing system và performance ✅ Updated
Middleware 30+ middleware ecosystem với YAML config ✅ Available
🔌 Adapters & Integration
Tài liệu Mô tả Trạng thái
Adapter Pattern Multi-engine HTTP support ✅ Updated
Error Handling Enterprise error management ✅ Available
Testing Testing utilities và best practices ✅ Available
📖 Additional Resources

📝 Examples

Khám phá các examples thực tế:

Basic Applications
Adapter Examples
Advanced Features

🤝 Contributing

Chúng tôi hoan nghênh mọi đóng góp cho Fork HTTP Framework!

Contribution Process
  1. Fork repository từ GitHub
  2. Tạo feature branch: git checkout -b feature/amazing-feature
  3. Commit changes: git commit -m 'Add amazing feature'
  4. Push branch: git push origin feature/amazing-feature
  5. Tạo Pull Request với detailed description
Development Setup
# Clone repository
git clone https://github.com/go-fork/fork.git
cd fork

# Install dependencies
go mod download

# Run tests
go test ./...

# Run benchmarks
go test -bench=. ./...

# Generate documentation
go doc -all
Code Standards
  • Follow Go best practices và gofmt formatting
  • Write comprehensive tests với coverage > 80%
  • Add detailed documentation cho public APIs
  • Include performance benchmarks cho critical paths
  • Use semantic versioning cho releases

📄 License

Fork HTTP Framework được phát hành dưới MIT License.

📚 Documentation
💻 Code & Examples
🌐 Community
🚀 Performance

Fork HTTP Framework - Build fast, scalable web applications in Go 🚀

Made with ❤️ by the Fork Team

Documentation

Overview

package app cung cấp một hệ thống HTTP linh hoạt và có thể mở rộng cho ứng dụng.

Package này sử dụng thiết kế dựa trên adapter pattern, cho phép sử dụng nhiều HTTP engine khác nhau (net/http, fasthttp, http2, quic-h3) với khả năng tùy chỉnh và mở rộng cao. Hỗ trợ đầy đủ các thành phần cần thiết cho việc xây dựng RESTful API, web services và ứng dụng web hiện đại.

Các tính năng chính:

  • Hỗ trợ nhiều HTTP engine thông qua adapter pattern
  • Router mạnh mẽ với hỗ trợ params và wildcard
  • Hệ thống middleware linh hoạt với middleware groups
  • Context API mạnh mẽ để quản lý request/response
  • Binding và validation cho request data (JSON, XML, Form)
  • Hỗ trợ nhiều định dạng response (JSON, XML, HTML, Blob)
  • Hệ thống xử lý lỗi HTTP nhất quán và mở rộng
  • Struct HttpError chung với status_code, message, details và error gốc
  • Hàm tạo lỗi cho tất cả các mã trạng thái HTTP phổ biến
  • Tích hợp sẵn với validation errors (422 Unprocessable Entity)
  • Chi tiết lỗi tùy chỉnh và lỗi gốc để debug
  • Triển khai error interface và hỗ trợ unwrapping
  • File uploads và file serving
  • Quản lý session và cookies
  • Tích hợp sẵn với Dependency Injection container
  • Middleware chains thống nhất giữa các adapter khác nhau
  • Xử lý handlers dạng chuỗi với Context.Next()
  • Thứ tự thực thi middleware nhất quán giữa các adapters
  • Xử lý chính xác chuỗi middleware khi abort request
  • Hỗ trợ đồng thời cho HTTP/1.1, HTTP/2 và HTTP/3 (QUIC)

Cấu trúc package:

  • adapter/: Các adapter cho các HTTP engine khác nhau
  • net.go: Adapter cho chuẩn net/http của Go
  • fasthttp.go: Adapter cho fasthttp - HTTP server hiệu suất cao
  • xhttp2.go: Adapter hỗ trợ HTTP/2
  • quic-h3.go: Adapter hỗ trợ HTTP/3 qua QUIC
  • context/: Quản lý request/response context
  • context.go: Context API chính
  • request.go: Request wrapper và utilities
  • response.go: Response wrapper và utilities
  • router/: Router và định tuyến đường dẫn
  • router.go: Router core, hỗ trợ routing và middleware
  • application.go: Quản lý ứng dụng HTTP, entry point chính
  • constants.go: Các hằng số và error messages
  • config.go: Cấu hình HTTP server và behavior
  • provider.go: ServiceProvider để tích hợp với container DI

Ví dụ sử dụng cơ bản:

// Khởi tạo container
c := container.NewContainer()

// Khởi tạo application
app := http.NewWebApp(c)

// Đăng ký route
app.GET("/users", func(ctx context.Context) {
	ctx.JSON(200, GetUsers())
})

// Sử dụng middleware
app.Use(Logger(), Recovery())

// Tạo route group với prefix
api := app.Group("/api")
api.Use(Auth()) // Middleware chỉ cho group này

// Đăng ký route trong group
api.GET("/profile", GetProfile)
api.POST("/settings", UpdateSettings)

// Khởi động server
app.Listen(":8080")

Thiết kế bảo mật:

  • Cung cấp các struct private (httpContext, httpRequest, httpResponse) chỉ có thể truy cập thông qua interface công khai
  • Kiểm soát chặt chẽ việc tiếp xúc với đối tượng nền tảng
  • Validation tích hợp để ngăn chặn các lỗ hổng phổ biến
  • Xử lý middleware chains an toàn, không cho phép truy cập trực tiếp vào handlers
  • Chuỗi xử lý request rõ ràng và có thể kiểm soát thông qua Context.Next()
  • Bảo vệ trạng thái Context với cơ chế abort để ngăn chặn việc xử lý không mong muốn
  • Đảm bảo thứ tự thực thi handlers nhất quán giữa các adapter khác nhau
  • Cơ chế nhất quán để quản lý middleware chains trong mọi adapter (Net, FastHTTP, HTTP/2, QUIC)
  • Bảo vệ toàn vẹn của chuỗi middleware thông qua các method Handlers() và SetHandlers()
  • Ngăn chặn truy cập trực tiếp vào handlers nội bộ của httpContext qua interface
  • Xử lý graceful shutdown để đảm bảo tất cả request đang xử lý được hoàn thành
  • Kiểm soát chặt chẽ việc tiếp xúc với các đối tượng http.Request và http.ResponseWriter

Testing:

  • Test files đầy đủ cho tất cả thành phần: context, request, response
  • Tests cho tất cả adapter (net/http, fasthttp, http2, quic-h3)
  • Tests bao phủ router và application
  • Đảm bảo code coverage cao và chất lượng code
  • Tests cho middleware chains và thứ tự thực thi
  • Tests cho các tình huống lỗi và edge cases
  • Kiểm tra đầy đủ quá trình xử lý chuỗi middleware và Context.Next()
  • Verify thứ tự thực thi middleware trong các adapter khác nhau
  • Tests cho các handlers dùng Abort() trong middleware chains
  • Kiểm tra phương thức Handlers() và SetHandlers() của Context
  • Nhất quán middleware execution giữa các HTTP engines
  • Benchmark performace của các adapter trong các tình huống khác nhau

Cách thức xử lý Middleware:

  • Mỗi middleware là một hàm nhận Context và gọi Next() để truyền request đến middleware tiếp theo
  • Các middleware được đăng ký thông qua phương thức Use() của WebApp hoặc RouteGroup
  • Thứ tự đăng ký middleware quyết định thứ tự thực thi
  • Khái niệm "onion model": middleware pre-process trước khi vào handler chính, post-process sau khi handler thực thi
  • Middleware có thể dùng Abort() để dừng chuỗi xử lý
  • Việc triển khai middleware nhất quán giữa các adapters khác nhau
  • WebApp hỗ trợ global middlewares và group-specific middlewares

Package này được thiết kế theo nguyên tắc SOLID, dễ dàng mở rộng và tùy chỉnh, phù hợp cho cả ứng dụng nhỏ và các hệ thống phân tán phức tạp.

Xử lý lỗi HTTP:

  • PAMM cung cấp struct HttpError để đại diện cho lỗi HTTP với mã trạng thái, thông báo và chi tiết
  • Hỗ trợ tạo các lỗi HTTP chuẩn (400, 401, 403, 404, 422, 500, v.v.)
  • Có thể đính kèm thông tin chi tiết tùy chỉnh và lỗi gốc
  • Các hàm tạo lỗi đơn giản: BadRequest, Unauthorized, Forbidden, NotFound, v.v.
  • Các hàm tạo lỗi đầy đủ: NewBadRequest, NewUnauthorized, NewForbidden, NewNotFound, v.v.
  • Tuân thủ interface error và hỗ trợ unwrapping thông qua errors.Unwrap
  • Có thể sử dụng với errors.Is và errors.As
  • Giữ cho xử lý lỗi nhất quán trong toàn bộ ứng dụng

Ví dụ sử dụng HttpError:

// Tạo lỗi 400 đơn giản
err := http.BadRequest("Thông tin không hợp lệ")
ctx.JSON(err.StatusCode, err)

// Tạo lỗi 404 với chi tiết và lỗi gốc
origErr := sql.ErrNoRows
details := map[string]interface{}{
	"user_id": 123,
}
err := http.NewNotFound("Người dùng không tồn tại", details, origErr)
ctx.JSON(err.StatusCode, err)

Xem thêm ví dụ trong /examples/infra/http/error_handling

Index

Constants

View Source
const (
	// MethodGet là HTTP GET method, được sử dụng để truy xuất dữ liệu.
	MethodGet = "GET"

	// MethodPost là HTTP POST method, được sử dụng để tạo dữ liệu mới.
	MethodPost = "POST"

	// MethodPut là HTTP PUT method, được sử dụng để cập nhật toàn bộ dữ liệu hiện có.
	MethodPut = "PUT"

	// MethodDelete là HTTP DELETE method, được sử dụng để xóa dữ liệu.
	MethodDelete = "DELETE"

	// MethodPatch là HTTP PATCH method, được sử dụng để cập nhật một phần dữ liệu.
	MethodPatch = "PATCH"

	// MethodHead là HTTP HEAD method, tương tự GET nhưng chỉ trả về headers.
	MethodHead = "HEAD"

	// MethodOptions là HTTP OPTIONS method, được sử dụng để truy vấn về các options giao tiếp.
	MethodOptions = "OPTIONS"

	// MethodTrace là HTTP TRACE method, được sử dụng để debugging.
	MethodTrace = "TRACE"

	// MethodConnect là HTTP CONNECT method, được sử dụng để thiết lập tunnel đến server.
	MethodConnect = "CONNECT"
)

HTTP Methods định nghĩa các HTTP methods chuẩn theo RFC7231 và RFC5789. Các constants này được sử dụng trong toàn bộ framework để định danh các HTTP methods.

View Source
const (
	// ContentTypeJSON là MIME type cho dữ liệu JSON.
	ContentTypeJSON = "application/json"

	// ContentTypeXML là MIME type cho dữ liệu XML.
	ContentTypeXML = "application/xml"

	// ContentTypeForm là MIME type cho form data được mã hóa URL.
	ContentTypeForm = "application/x-www-form-urlencoded"

	// ContentTypeFormMultipart là MIME type cho multipart form data.
	ContentTypeFormMultipart = "multipart/form-data"

	// ContentTypePlain là MIME type cho plain text.
	ContentTypePlain = "text/plain"

	// ContentTypeHTML là MIME type cho HTML content.
	ContentTypeHTML = "text/html"

	// ContentTypeEventStream là MIME type cho server-sent events.
	ContentTypeEventStream = "text/event-stream"

	// ContentTypeProtobuf là MIME type cho Protocol Buffers.
	ContentTypeProtobuf = "application/protobuf"

	// ContentTypeOctetStream là MIME type cho binary data.
	ContentTypeOctetStream = "application/octet-stream"

	// ContentTypePDF là MIME type cho PDF documents.
	ContentTypePDF = "application/pdf"
)

Content types định nghĩa các MIME types phổ biến cho HTTP content. Các constants này được sử dụng để thiết lập và kiểm tra Content-Type header.

View Source
const (
	// HeaderAccept chỉ định media types được client chấp nhận.
	HeaderAccept = "Accept"

	// HeaderAcceptEncoding chỉ định encoding algorithms được client chấp nhận.
	HeaderAcceptEncoding = "Accept-Encoding"

	// HeaderAcceptLanguage chỉ định ngôn ngữ được client ưa thích.
	HeaderAcceptLanguage = "Accept-Language"

	// HeaderAllow liệt kê các HTTP methods được phép cho resource.
	HeaderAllow = "Allow"

	// HeaderAuthorization chứa thông tin xác thực của client.
	HeaderAuthorization = "Authorization"

	// HeaderContentDisposition chỉ định cách xử lý content (inline hoặc attachment).
	HeaderContentDisposition = "Content-Disposition"

	// HeaderContentEncoding chỉ định encoding đã áp dụng cho body.
	HeaderContentEncoding = "Content-Encoding"

	// HeaderContentLength chỉ định kích thước của body tính bằng bytes.
	HeaderContentLength = "Content-Length"

	// HeaderContentType chỉ định media type của body.
	HeaderContentType = "Content-Type"

	// HeaderCookie chứa HTTP cookies gửi từ client.
	HeaderCookie = "Cookie"

	// HeaderSetCookie được server sử dụng để gửi cookies đến client.
	HeaderSetCookie = "Set-Cookie"

	// HeaderIfModifiedSince được sử dụng với GET để request chỉ khi resource đã thay đổi.
	HeaderIfModifiedSince = "If-Modified-Since"

	// HeaderLastModified chỉ định thời điểm resource được sửa đổi lần cuối.
	HeaderLastModified = "Last-Modified"

	// HeaderLocation chỉ định URL mà client nên chuyển hướng đến.
	HeaderLocation = "Location"

	// HeaderUpgrade yêu cầu server chuyển đổi sang protocol khác.
	HeaderUpgrade = "Upgrade"

	// HeaderVary chỉ định các headers ảnh hưởng đến cách server chọn representation.
	HeaderVary = "Vary"

	// HeaderWWWAuthenticate chỉ định phương thức xác thực cho resource.
	HeaderWWWAuthenticate = "WWW-Authenticate"

	// HeaderXForwardedFor chứa địa chỉ IP của client khi qua proxy.
	HeaderXForwardedFor = "X-Forwarded-For"

	// HeaderXForwardedProto chứa protocol ban đầu của request.
	HeaderXForwardedProto = "X-Forwarded-Proto"

	// HeaderXForwardedProtocol tương tự HeaderXForwardedProto.
	HeaderXForwardedProtocol = "X-Forwarded-Protocol"

	// HeaderXForwardedHost chứa host ban đầu của request.
	HeaderXForwardedHost = "X-Forwarded-Host"

	// HeaderXRealIP chứa địa chỉ IP thật của client khi qua proxy.
	HeaderXRealIP = "X-Real-IP"

	// HeaderXRequestID chứa ID duy nhất của request để tracking.
	HeaderXRequestID = "X-Request-ID"

	// HeaderXRequestedWith chứa thông tin về loại request (AJAX, v.v.).
	HeaderXRequestedWith = "X-Requested-With"

	// HeaderServer chứa thông tin về server phục vụ request.
	HeaderServer = "Server"

	// HeaderOrigin chỉ định origin của request (CORS).
	HeaderOrigin = "Origin"

	// HeaderAccessControlRequestMethod chỉ định method trong preflight request (CORS).
	HeaderAccessControlRequestMethod = "Access-Control-Request-Method"

	// HeaderAccessControlRequestHeaders chỉ định headers trong preflight request (CORS).
	HeaderAccessControlRequestHeaders = "Access-Control-Request-Headers"

	// HeaderAccessControlAllowOrigin chỉ định origins được phép truy cập (CORS).
	HeaderAccessControlAllowOrigin = "Access-Control-Allow-Origin"

	// HeaderAccessControlAllowMethods chỉ định methods được phép (CORS).
	HeaderAccessControlAllowMethods = "Access-Control-Allow-Methods"

	// HeaderAccessControlAllowHeaders chỉ định headers được phép (CORS).
	HeaderAccessControlAllowHeaders = "Access-Control-Allow-Headers"

	// HeaderAccessControlAllowCredentials cho phép gửi credentials (CORS).
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"

	// HeaderAccessControlExposeHeaders chỉ định headers mà browser có thể truy cập (CORS).
	HeaderAccessControlExposeHeaders = "Access-Control-Expose-Headers"

	// HeaderAccessControlMaxAge chỉ định thời gian cache preflight request (CORS).
	HeaderAccessControlMaxAge = "Access-Control-Max-Age"

	// HeaderStrictTransportSecurity yêu cầu browser chỉ kết nối qua HTTPS (HSTS).
	HeaderStrictTransportSecurity = "Strict-Transport-Security"

	// HeaderXContentTypeOptions ngăn chặn MIME-type sniffing (bảo mật).
	HeaderXContentTypeOptions = "X-Content-Type-Options"

	// HeaderXXSSProtection kích hoạt bảo vệ XSS của browser.
	HeaderXXSSProtection = "X-XSS-Protection"

	// HeaderXFrameOptions kiểm soát việc nhúng trang trong frames (clickjacking).
	HeaderXFrameOptions = "X-Frame-Options"

	// HeaderContentSecurityPolicy định nghĩa chính sách bảo mật content (CSP).
	HeaderContentSecurityPolicy = "Content-Security-Policy"

	// HeaderXCSRFToken chứa token CSRF để bảo vệ chống lại tấn công CSRF.
	HeaderXCSRFToken = "X-CSRF-Token"
)

Header names định nghĩa các HTTP header phổ biến theo RFC7231. Các constants này được sử dụng để truy cập và thiết lập HTTP headers.

View Source
const (
	// MIMEWebAppJSON là MIME type cho JSON.
	MIMEWebAppJSON = "application/json"

	// MIMEWebAppJSONCharsetUTF8 là MIME type cho JSON với charset UTF-8.
	MIMEWebAppJSONCharsetUTF8 = "application/json; charset=utf-8"

	// MIMEWebAppXML là MIME type cho XML.
	MIMEWebAppXML = "application/xml"

	// MIMEWebAppXMLCharsetUTF8 là MIME type cho XML với charset UTF-8.
	MIMEWebAppXMLCharsetUTF8 = "application/xml; charset=utf-8"

	// MIMETextXML là MIME type cho XML dạng text.
	MIMETextXML = "text/xml"

	// MIMETextXMLCharsetUTF8 là MIME type cho XML dạng text với charset UTF-8.
	MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8"

	// MIMEWebAppForm là MIME type cho form data được mã hóa URL.
	MIMEWebAppForm = "application/x-www-form-urlencoded"

	// MIMEWebAppProtobuf là MIME type cho Protocol Buffers.
	MIMEWebAppProtobuf = "application/protobuf"

	// MIMEWebAppMsgpack là MIME type cho MessagePack.
	MIMEWebAppMsgpack = "application/msgpack"

	// MIMETextHTML là MIME type cho HTML.
	MIMETextHTML = "text/html"

	// MIMETextHTMLCharsetUTF8 là MIME type cho HTML với charset UTF-8.
	MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8"

	// MIMETextPlain là MIME type cho plain text.
	MIMETextPlain = "text/plain"

	// MIMETextPlainCharsetUTF8 là MIME type cho plain text với charset UTF-8.
	MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8"

	// MIMEMultipartForm là MIME type cho multipart form data.
	MIMEMultipartForm = "multipart/form-data"

	// MIMEOctetStream là MIME type cho binary data.
	MIMEOctetStream = "application/octet-stream"
)

MIME types định nghĩa các media type đầy đủ với charset. Các constants này được sử dụng để thiết lập Content-Type header.

View Source
const (
	// StatusContinue (100) - Server đã nhận được request headers và client nên tiếp tục gửi request body.
	StatusContinue = http.StatusContinue // 100

	// StatusSwitchingProtocols (101) - Server đang chuyển đổi sang protocol khác theo yêu cầu của client.
	StatusSwitchingProtocols = http.StatusSwitchingProtocols // 101

	// StatusProcessing (102) - Server đang xử lý request nhưng chưa có response sẵn có.
	StatusProcessing = http.StatusProcessing // 102

	// StatusOK (200) - Request đã thành công.
	StatusOK = http.StatusOK // 200

	// StatusCreated (201) - Request đã thành công và một resource mới đã được tạo.
	StatusCreated = http.StatusCreated // 201

	// StatusAccepted (202) - Request đã được chấp nhận để xử lý nhưng chưa hoàn thành.
	StatusAccepted = http.StatusAccepted // 202

	// StatusNonAuthoritativeInfo (203) - Response chứa thông tin không chính thức.
	StatusNonAuthoritativeInfo = http.StatusNonAuthoritativeInfo // 203

	// StatusNoContent (204) - Server đã xử lý thành công request nhưng không trả về body.
	StatusNoContent = http.StatusNoContent // 204

	// StatusResetContent (205) - Server đã xử lý request và client nên reset document view.
	StatusResetContent = http.StatusResetContent // 205

	// StatusPartialContent (206) - Server đã xử lý một phần của request (range request).
	StatusPartialContent = http.StatusPartialContent // 206

	// StatusMultiStatus (207) - Response chứa nhiều status codes cho nhiều sub-requests.
	StatusMultiStatus = http.StatusMultiStatus // 207

	// StatusAlreadyReported (208) - Members đã được báo cáo trước đó.
	StatusAlreadyReported = http.StatusAlreadyReported // 208

	// StatusIMUsed (226) - Server đã thực hiện request cho resource và response là biểu diễn của tập hợp các manipulations.
	StatusIMUsed = http.StatusIMUsed // 226

	// StatusMultipleChoices (300) - Request có nhiều hơn một khả năng phản hồi.
	StatusMultipleChoices = http.StatusMultipleChoices // 300

	// StatusMovedPermanently (301) - Resource đã được di chuyển vĩnh viễn sang URL mới.
	StatusMovedPermanently = http.StatusMovedPermanently // 301

	// StatusFound (302) - Resource tạm thời được tìm thấy ở một URL khác.
	StatusFound = http.StatusFound // 302

	// StatusSeeOther (303) - Client nên lấy resource từ URL khác bằng GET method.
	StatusSeeOther = http.StatusSeeOther // 303

	// StatusNotModified (304) - Resource không bị sửa đổi kể từ phiên bản đã cached.
	StatusNotModified = http.StatusNotModified // 304

	// StatusUseProxy (305) - Resource phải được truy cập thông qua proxy.
	StatusUseProxy = http.StatusUseProxy // 305

	// StatusTemporaryRedirect (307) - Resource tạm thời được chuyển hướng sang một URL khác.
	StatusTemporaryRedirect = http.StatusTemporaryRedirect // 307

	// StatusPermanentRedirect (308) - Resource đã được di chuyển vĩnh viễn sang URL mới.
	StatusPermanentRedirect = http.StatusPermanentRedirect // 308

	// StatusBadRequest (400) - Server không thể xử lý request do cú pháp không hợp lệ.
	StatusBadRequest = http.StatusBadRequest // 400

	// StatusUnauthorized (401) - Request yêu cầu xác thực người dùng.
	StatusUnauthorized = http.StatusUnauthorized // 401

	// StatusPaymentRequired (402) - Yêu cầu thanh toán để tiếp tục xử lý.
	StatusPaymentRequired = http.StatusPaymentRequired // 402

	// StatusForbidden (403) - Server hiểu request nhưng từ chối cấp quyền.
	StatusForbidden = http.StatusForbidden // 403

	// StatusNotFound (404) - Server không tìm thấy resource được yêu cầu.
	StatusNotFound = http.StatusNotFound // 404

	// StatusMethodNotAllowed (405) - Method không được cho phép cho resource.
	StatusMethodNotAllowed = http.StatusMethodNotAllowed // 405

	// StatusNotAcceptable (406) - Không thể tạo response thỏa mãn header Accept.
	StatusNotAcceptable = http.StatusNotAcceptable // 406

	// StatusProxyAuthRequired (407) - Yêu cầu xác thực proxy.
	StatusProxyAuthRequired = http.StatusProxyAuthRequired // 407

	// StatusRequestTimeout (408) - Server đã hết thời gian chờ đợi request.
	StatusRequestTimeout = http.StatusRequestTimeout // 408

	// StatusConflict (409) - Request xung đột với trạng thái hiện tại của resource.
	StatusConflict = http.StatusConflict // 409

	// StatusGone (410) - Resource đã không còn tồn tại vĩnh viễn.
	StatusGone = http.StatusGone // 410

	// StatusLengthRequired (411) - Content-Length header là bắt buộc.
	StatusLengthRequired = http.StatusLengthRequired // 411

	// StatusPreconditionFailed (412) - Điều kiện tiên quyết không được đáp ứng.
	StatusPreconditionFailed = http.StatusPreconditionFailed // 412

	// StatusRequestEntityTooLarge (413) - Request entity quá lớn.
	StatusRequestEntityTooLarge = http.StatusRequestEntityTooLarge // 413

	// StatusRequestURITooLong (414) - Request URI quá dài.
	StatusRequestURITooLong = http.StatusRequestURITooLong // 414

	// StatusUnsupportedMediaType (415) - Media type không được hỗ trợ.
	StatusUnsupportedMediaType = http.StatusUnsupportedMediaType // 415

	// StatusRequestedRangeNotSatisfiable (416) - Range request không thể được đáp ứng.
	StatusRequestedRangeNotSatisfiable = http.StatusRequestedRangeNotSatisfiable // 416

	// StatusExpectationFailed (417) - Expect header không thể được đáp ứng.
	StatusExpectationFailed = http.StatusExpectationFailed // 417

	// StatusTeapot (418) - "I'm a teapot" - RFC 2324 (April Fools' joke).
	StatusTeapot = http.StatusTeapot // 418

	// StatusMisdirectedRequest (421) - Request đã được chuyển hướng đến server không thể tạo response.
	StatusMisdirectedRequest = http.StatusMisdirectedRequest // 421

	// StatusUnprocessableEntity (422) - Request hợp lệ nhưng không thể xử lý.
	StatusUnprocessableEntity = http.StatusUnprocessableEntity // 422

	// StatusLocked (423) - Resource bị khóa.
	StatusLocked = http.StatusLocked // 423

	// StatusFailedDependency (424) - Request thất bại do phụ thuộc vào request khác đã thất bại.
	StatusFailedDependency = http.StatusFailedDependency // 424

	// StatusTooEarly (425) - Server không sẵn sàng xử lý request vì có thể bị tấn công replay.
	StatusTooEarly = http.StatusTooEarly // 425

	// StatusUpgradeRequired (426) - Client nên chuyển sang protocol khác.
	StatusUpgradeRequired = http.StatusUpgradeRequired // 426

	// StatusPreconditionRequired (428) - Origin server yêu cầu request phải có điều kiện.
	StatusPreconditionRequired = http.StatusPreconditionRequired // 428

	// StatusTooManyRequests (429) - Client đã gửi quá nhiều requests trong một khoảng thời gian.
	StatusTooManyRequests = http.StatusTooManyRequests // 429

	// StatusRequestHeaderFieldsTooLarge (431) - Header fields quá lớn.
	StatusRequestHeaderFieldsTooLarge = http.StatusRequestHeaderFieldsTooLarge // 431

	// StatusUnavailableForLegalReasons (451) - Resource không khả dụng vì lý do pháp lý.
	StatusUnavailableForLegalReasons = http.StatusUnavailableForLegalReasons // 451

	// StatusInternalServerError (500) - Lỗi nội bộ server không xác định.
	StatusInternalServerError = http.StatusInternalServerError // 500

	// StatusNotImplemented (501) - Method không được server hỗ trợ.
	StatusNotImplemented = http.StatusNotImplemented // 501

	// StatusBadGateway (502) - Server, trong vai trò gateway, nhận được response không hợp lệ.
	StatusBadGateway = http.StatusBadGateway // 502

	// StatusServiceUnavailable (503) - Server tạm thời không khả dụng.
	StatusServiceUnavailable = http.StatusServiceUnavailable // 503

	// StatusGatewayTimeout (504) - Server, trong vai trò gateway, không nhận được response kịp thời.
	StatusGatewayTimeout = http.StatusGatewayTimeout // 504

	// StatusHTTPVersionNotSupported (505) - Phiên bản HTTP không được hỗ trợ.
	StatusHTTPVersionNotSupported = http.StatusHTTPVersionNotSupported // 505

	// StatusVariantAlsoNegotiates (506) - Cấu hình nội bộ server không chính xác.
	StatusVariantAlsoNegotiates = http.StatusVariantAlsoNegotiates // 506

	// StatusInsufficientStorage (507) - Server không đủ storage để hoàn thành request.
	StatusInsufficientStorage = http.StatusInsufficientStorage // 507

	// StatusLoopDetected (508) - Server phát hiện vòng lặp vô hạn trong request.
	StatusLoopDetected = http.StatusLoopDetected // 508

	// StatusNotExtended (510) - Yêu cầu thêm extensions để hoàn thành request.
	StatusNotExtended = http.StatusNotExtended // 510

	// StatusNetworkAuthenticationRequired (511) - Client cần xác thực để truy cập network.
	StatusNetworkAuthenticationRequired = http.StatusNetworkAuthenticationRequired // 511
)

HTTP status định nghĩa các HTTP status codes theo RFC7231, RFC6585 và RFC4918. Các constants này giúp xác định trạng thái của HTTP response.

View Source
const (
	// AdapterTypeNetHTTP là adapter cho Go's standard net/http package.
	AdapterTypeNetHTTP = "net/http"

	// AdapterTypeFastHTTP là adapter cho thư viện fasthttp với hiệu suất cao hơn.
	AdapterTypeFastHTTP = "fasthttp"

	// AdapterTypeHTTP2 là adapter cho HTTP/2 protocol.
	AdapterTypeHTTP2 = "http2"

	// AdapterTypeQuicH3 là adapter cho QUIC và HTTP/3 protocol.
	AdapterTypeQuicH3 = "quic-h3"
)

Adapter engine types định nghĩa các loại HTTP server engine hỗ trợ. Các constants này được sử dụng để xác định loại adapter đang được sử dụng.

Variables

View Source
var (
	// ErrServerNotRunning được trả về khi cố gắng thao tác với server chưa được khởi động.
	// Điều này xảy ra khi cố gắng thực hiện các hoạt động yêu cầu server đang chạy.
	ErrServerNotRunning = errors.New("http: server not running")

	// ErrInvalidMethod được trả về khi HTTP method không hợp lệ hoặc không được hỗ trợ.
	// Điều này xảy ra khi client sử dụng một HTTP method không chuẩn hoặc không được server hỗ trợ.
	ErrInvalidMethod = errors.New("http: invalid method")

	// ErrUnsupportedMediaType được trả về khi nội dung request có Content-Type không được hỗ trợ.
	// Điều này xảy ra khi server không thể xử lý định dạng dữ liệu mà client gửi.
	ErrUnsupportedMediaType = errors.New("http: unsupported media type")

	// ErrNotFound được trả về khi resource không tồn tại.
	// Điều này xảy ra khi client yêu cầu một resource không có trên server.
	ErrNotFound = errors.New("http: not found")

	// ErrMethodNotAllowed được trả về khi method không được phép cho resource.
	// Điều này xảy ra khi resource tồn tại nhưng không hỗ trợ HTTP method đã yêu cầu.
	ErrMethodNotAllowed = errors.New("http: method not allowed")

	// ErrBadRequest được trả về khi request không hợp lệ.
	// Điều này xảy ra khi định dạng request không đúng hoặc thiếu thông tin bắt buộc.
	ErrBadRequest = errors.New("http: bad request")

	// ErrInternalServerError được trả về khi có lỗi không xác định từ server.
	// Điều này xảy ra khi server gặp lỗi mà không thể xử lý một cách bình thường.
	ErrInternalServerError = errors.New("http: internal server error")

	// ErrUnauthorized được trả về khi client chưa được xác thực.
	// Điều này xảy ra khi client cố gắng truy cập resource yêu cầu xác thực nhưng chưa đăng nhập.
	ErrUnauthorized = errors.New("http: unauthorized")

	// ErrForbidden được trả về khi client bị từ chối quyền truy cập.
	// Điều này xảy ra khi client đã xác thực nhưng không có đủ quyền truy cập resource.
	ErrForbidden = errors.New("http: forbidden")

	// ErrRequestTimeout được trả về khi xử lý request vượt quá thời gian cho phép.
	// Điều này xảy ra khi server không thể hoàn thành xử lý request trong thời gian giới hạn.
	ErrRequestTimeout = errors.New("http: request timeout")

	// ErrRouteNotFound được trả về khi không tìm thấy route cho request.
	// Điều này xảy ra khi URL path được yêu cầu không khớp với bất kỳ route nào đã đăng ký.
	ErrRouteNotFound = errors.New("http: route not found")

	// ErrUnsupportedBinding được trả về khi kiểu binding không được hỗ trợ.
	// Điều này xảy ra khi cố gắng bind request body vào một kiểu dữ liệu không hỗ trợ.
	ErrUnsupportedBinding = errors.New("http: unsupported binding")

	// ErrUnsupportedRendering được trả về khi kiểu rendering không được hỗ trợ.
	// Điều này xảy ra khi cố gắng render response trong một định dạng không hỗ trợ.
	ErrUnsupportedRendering = errors.New("http: unsupported rendering")

	// ErrValidationFailed được trả về khi validation của request body thất bại.
	// Điều này xảy ra khi dữ liệu đầu vào không đáp ứng các quy tắc validation.
	ErrValidationFailed = errors.New("http: validation failed")

	// ErrInvalidBinding được trả về khi không thể bind request body vào struct.
	// Điều này xảy ra khi định dạng của request body không khớp với cấu trúc đích.
	ErrInvalidBinding = errors.New("http: invalid binding")

	// ErrInvalidCertificate được trả về khi tệp chứng chỉ SSL/TLS không hợp lệ hoặc không tồn tại.
	// Điều này xảy ra khi cố gắng khởi động HTTPS server với chứng chỉ không hợp lệ.
	ErrInvalidCertificate = errors.New("http: invalid certificate")

	// ErrInvalidRequestBody được trả về khi request body không hợp lệ hoặc không đọc được.
	// Điều này xảy ra khi body không thể được parse hoặc có định dạng không hợp lệ.
	ErrInvalidRequestBody = errors.New("http: invalid request body")

	// ErrAdapterNotFound được trả về khi không tìm thấy adapter được yêu cầu.
	// Điều này xảy ra khi cố gắng sử dụng một adapter không tồn tại hoặc không được đăng ký.
	ErrAdapterNotFound = errors.New("http: adapter not found")

	// ErrAdapterNotSet được trả về khi cố gắng chạy server mà không thiết lập adapter.
	// Điều này xảy ra khi gọi Run() hoặc RunTLS() trước khi gọi SetAdapter().
	ErrAdapterNotSet = errors.New("http: adapter not set")

	// ErrInvalidContext được trả về khi context không hợp lệ hoặc đã hết hạn.
	// Điều này xảy ra khi cố gắng truy cập context đã hết hạn hoặc bị hủy.
	ErrInvalidContext = errors.New("invalid or expired context")

	// ErrServerAlreadyRunning được trả về khi cố gắng khởi động server đã chạy.
	// Điều này xảy ra khi gọi Run() hoặc RunTLS() nhiều lần.
	ErrServerAlreadyRunning = errors.New("server is already running")

	// ErrInvalidConfiguration được trả về khi cấu hình không hợp lệ.
	// Điều này xảy ra khi các giá trị cấu hình không đúng định dạng hoặc nằm ngoài phạm vi cho phép.
	ErrInvalidConfiguration = errors.New("invalid configuration")
)

Errors định nghĩa các lỗi tiêu chuẩn của framework. Các error constants này được sử dụng để thông báo lỗi trong toàn bộ framework.

Functions

func NewServiceProvider

func NewServiceProvider() di.ServiceProvider

NewServiceProvider tạo một instance mới của HTTP service provider. Provider này được sử dụng để đăng ký HTTP framework vào application container.

Returns:

  • di.ServiceProvider: Provider được sử dụng để đăng ký HTTP services

Types

type GracefulShutdownConfig

type GracefulShutdownConfig struct {
	// Enabled bật/tắt graceful shutdown
	// Mặc định: true
	Enabled bool `mapstructure:"enabled" yaml:"enabled"`

	// Timeout thời gian tối đa để chờ graceful shutdown (seconds)
	// Mặc định: 30 seconds
	Timeout int `mapstructure:"timeout" yaml:"timeout"`

	// WaitForConnections có chờ tất cả connections kết thúc không
	// Mặc định: true
	WaitForConnections bool `mapstructure:"wait_for_connections" yaml:"wait_for_connections"`

	// SignalBufferSize kích thước buffer cho signal channel
	// Mặc định: 1
	SignalBufferSize int `mapstructure:"signal_buffer_size" yaml:"signal_buffer_size"`

	// OnShutdownStart callback được gọi khi bắt đầu shutdown
	OnShutdownStart func() `mapstructure:"-" yaml:"-"`

	// OnShutdownComplete callback được gọi khi shutdown hoàn thành
	OnShutdownComplete func() `mapstructure:"-" yaml:"-"`

	// OnShutdownError callback được gọi khi có lỗi trong quá trình shutdown
	OnShutdownError func(error) `mapstructure:"-" yaml:"-"`
}

GracefulShutdownConfig chứa cấu hình cho graceful shutdown

func (*GracefulShutdownConfig) MergeConfig

func (g *GracefulShutdownConfig) MergeConfig(other *GracefulShutdownConfig)

MergeConfig hợp nhất cấu hình graceful shutdown

func (*GracefulShutdownConfig) Validate

func (g *GracefulShutdownConfig) Validate() error

Validate kiểm tra tính hợp lệ của cấu hình graceful shutdown

type ServiceProvider

type ServiceProvider struct{}

ServiceProvider là đối tượng thực hiện việc đăng ký và khởi tạo HTTP framework vào container dependency injection. Nó tuân theo interface ServiceProvider của package di để tích hợp với hệ thống service container.

func (*ServiceProvider) Boot

func (p *ServiceProvider) Boot(app di.Application)

Boot được gọi sau khi tất cả các service provider đã được đăng ký. Phương thức này cấu hình HTTP WebApp bằng cách thiết lập adapter từ thông tin trong config và load WebApp config từ provider.

Parameters:

  • app: Instance của application chứa container DI

Panics:

  • Nếu app là nil
  • Nếu container là nil
  • Nếu không tìm thấy required services (http, log, config)
  • Nếu type assertion thất bại cho services
  • Nếu không tìm thấy adapter trong config
  • Nếu config loading hoặc validation thất bại (handled by LoadConfigFromProvider)
  • Nếu unmarshal config thất bại (handled by LoadConfigFromProvider)

func (*ServiceProvider) Providers

func (p *ServiceProvider) Providers() []string

Providers trả về danh sách các service mà HTTP service provider đăng ký.

Returns:

  • []string: Mảng các tên services được đăng ký

func (*ServiceProvider) Register

func (p *ServiceProvider) Register(app di.Application)

Register đăng ký các binding liên quan đến HTTP framework vào container. Phương thức này tạo một HTTP WebApp instance và đăng ký nó vào container để các thành phần khác của ứng dụng có thể truy cập.

Parameters:

  • app: Instance của application chứa container DI

Panics:

  • Nếu app là nil
  • Nếu container là nil
  • Nếu không thể đăng ký binding hoặc alias

func (*ServiceProvider) Requires

func (p *ServiceProvider) Requires() []string

Requires trả về danh sách các provider mà HTTP service provider phụ thuộc vào.

Returns:

  • []string: Mảng các tên providers được yêu cầu

type WebApp

type WebApp struct {
	// contains filtered or unexported fields
}

WebApp là đối tượng chính của framework, quản lý HTTP server và routing. Nó hoạt động như một wrapper cho router và adapter, cung cấp API đồng nhất để xử lý HTTP requests, đăng ký routes và middlewares. WebApp khác biệt với DI Application - WebApp chỉ quản lý web layer.

func NewWebApp

func NewWebApp() *WebApp

NewWebApp tạo một instance mới của WebApp. Hàm này khởi tạo router và mảng middlewares rỗng.

Returns:

  • *WebApp: Một WebApp mới đã được khởi tạo

func (*WebApp) Any

func (app *WebApp) Any(path string, handlers ...router.HandlerFunc)

Any đăng ký handler cho tất cả các HTTP methods phổ biến. Handler sẽ được đăng ký cho GET, POST, PUT, DELETE, PATCH, HEAD và OPTIONS.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) CleanupResources

func (app *WebApp) CleanupResources()

CleanupResources dọn dẹp tài nguyên không sử dụng để tránh memory leaks

func (*WebApp) DELETE

func (app *WebApp) DELETE(path string, handlers ...router.HandlerFunc)

DELETE đăng ký handler cho HTTP DELETE method. HTTP DELETE thường được sử dụng để xóa dữ liệu.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) EnableSecurityMiddleware

func (app *WebApp) EnableSecurityMiddleware()

EnableSecurityMiddleware bật các middleware bảo mật tự động Note: Security headers are now handled by the helmet middleware package. Request size, method validation, and timeout are handled by their respective middleware packages: - bodylimit: handles max_request_body_size - method: handles allowed_methods - timeout: handles request_timeout - helmet: handles enable_security_headers

func (*WebApp) GET

func (app *WebApp) GET(path string, handlers ...router.HandlerFunc)

GET đăng ký handler cho HTTP GET method. HTTP GET thường được sử dụng để truy xuất dữ liệu.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) GetActiveConnections

func (app *WebApp) GetActiveConnections() int32

GetActiveConnections trả về số lượng connections đang hoạt động

func (*WebApp) GetAdapter

func (app *WebApp) GetAdapter() adapter.Adapter

GetAdapter trả về adapter hiện tại của WebApp. Adapter là interface giao tiếp với HTTP server cơ bản.

Returns:

  • adapter.Adapter: Adapter hiện tại của WebApp

func (*WebApp) GetConfig

func (app *WebApp) GetConfig() *WebAppConfig

GetConfig trả về cấu hình hiện tại của WebApp.

Returns:

  • *WebAppConfig: Cấu hình hiện tại của WebApp

func (*WebApp) GracefulShutdown

func (app *WebApp) GracefulShutdown() error

GracefulShutdown thực hiện graceful shutdown với cấu hình nâng cao Phương thức này xử lý signals, timeout và connection tracking

Returns:

  • error: Lỗi nếu có trong quá trình graceful shutdown

func (*WebApp) Group

func (app *WebApp) Group(prefix string) router.Router

Group tạo một router group mới với prefix đường dẫn. Group cho phép tổ chức routes theo cấu trúc thư mục và áp dụng middleware cho một nhóm routes.

Parameters:

  • prefix: Tiền tố đường dẫn cho group

Returns:

  • router.Router: Router mới đã được tạo với prefix đã chỉ định

func (*WebApp) HEAD

func (app *WebApp) HEAD(path string, handlers ...router.HandlerFunc)

HEAD đăng ký handler cho HTTP HEAD method. HTTP HEAD tương tự như GET nhưng chỉ trả về headers không có body.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) Handle

func (app *WebApp) Handle(method, path string, handlers ...router.HandlerFunc)

Handle đăng ký handler cho một HTTP method cụ thể. Đây là phương thức tổng quát cho phép đăng ký handler với bất kỳ HTTP method nào.

Parameters:

  • method: HTTP method cần đăng ký (GET, POST, PUT, DELETE, v.v.)
  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) IsShuttingDown

func (app *WebApp) IsShuttingDown() bool

IsShuttingDown kiểm tra xem WebApp có đang trong quá trình shutdown không

func (*WebApp) ListenForShutdownSignals

func (app *WebApp) ListenForShutdownSignals()

ListenForShutdownSignals lắng nghe các signals để thực hiện graceful shutdown Hàm này chạy trong goroutine riêng và tự động shutdown khi nhận signals

func (*WebApp) NewContext

func (app *WebApp) NewContext(w http.ResponseWriter, r *http.Request) forkCtx.Context

NewContext tạo một context mới để xử lý HTTP request/response. Context cung cấp các tiện ích để truy cập request và xử lý response.

Parameters:

  • w: HTTP response writer
  • r: HTTP request

Returns:

  • forkCtx.Context: Context mới đã được khởi tạo

func (*WebApp) OPTIONS

func (app *WebApp) OPTIONS(path string, handlers ...router.HandlerFunc)

OPTIONS đăng ký handler cho HTTP OPTIONS method. HTTP OPTIONS thường được sử dụng để truy vấn thông tin về communication options.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) PATCH

func (app *WebApp) PATCH(path string, handlers ...router.HandlerFunc)

PATCH đăng ký handler cho HTTP PATCH method. HTTP PATCH thường được sử dụng để cập nhật một phần dữ liệu.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) POST

func (app *WebApp) POST(path string, handlers ...router.HandlerFunc)

POST đăng ký handler cho HTTP POST method. HTTP POST thường được sử dụng để tạo dữ liệu mới.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) PUT

func (app *WebApp) PUT(path string, handlers ...router.HandlerFunc)

PUT đăng ký handler cho HTTP PUT method. HTTP PUT thường được sử dụng để cập nhật toàn bộ dữ liệu.

Parameters:

  • path: Đường dẫn URL để đăng ký handler
  • handlers: Danh sách các handlers xử lý request

func (*WebApp) Router

func (app *WebApp) Router() router.Router

Router trả về router hiện tại của WebApp. Router chịu trách nhiệm quản lý routes và điều hướng requests.

Returns:

  • router.Router: Router hiện tại của WebApp

func (*WebApp) RunTLS

func (app *WebApp) RunTLS(certFile, keyFile string) error

RunTLS khởi động HTTPS server với các tệp chứng chỉ SSL/TLS đã chỉ định. Server sẽ lắng nghe và xử lý các HTTPS requests theo cấu hình từ adapter.

Parameters:

  • certFile: Đường dẫn đến tệp chứng chỉ SSL/TLS
  • keyFile: Đường dẫn đến tệp khóa SSL/TLS

Returns:

  • error: Lỗi nếu có trong quá trình khởi động server

Errors:

  • ErrAdapterNotSet: Trả về khi adapter chưa được thiết lập
  • ErrInvalidCertificate: Trả về khi tệp chứng chỉ hoặc tệp khóa không hợp lệ

func (*WebApp) Serve

func (app *WebApp) Serve() error

Run khởi động HTTP server sử dụng adapter hiện tại. Server sẽ lắng nghe và xử lý các HTTP requests theo cấu hình từ adapter.

Returns:

  • error: Lỗi nếu có trong quá trình khởi động server

Errors:

  • ErrAdapterNotSet: Trả về khi adapter chưa được thiết lập

func (*WebApp) ServeHTTP

func (app *WebApp) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP xử lý HTTP request và implement interface http.Handler. Phương thức này cho phép WebApp hoạt động như một HTTP handler.

Parameters:

  • w: HTTP response writer để ghi response
  • r: HTTP request cần xử lý

func (*WebApp) ServeWithGracefulShutdown

func (app *WebApp) ServeWithGracefulShutdown() error

ServeWithGracefulShutdown khởi động server với graceful shutdown tự động Phương thức này tự động lắng nghe shutdown signals và thực hiện graceful shutdown

Returns:

  • error: Lỗi nếu có trong quá trình khởi động hoặc shutdown server

func (*WebApp) SetAdapter

func (app *WebApp) SetAdapter(adapter adapter.Adapter)

SetAdapter thiết lập adapter cho WebApp và cấu hình handler cho adapter. Adapter được sử dụng để giao tiếp với server HTTP.

Parameters:

  • adapter: Adapter cần thiết lập

func (*WebApp) SetConfig

func (app *WebApp) SetConfig(config *WebAppConfig)

SetConfig thiết lập cấu hình cho WebApp.

Parameters:

  • config: Cấu hình mới cho WebApp

func (*WebApp) SetShutdownTimeout

func (app *WebApp) SetShutdownTimeout(timeout time.Duration)

SetShutdownTimeout thiết lập timeout cho graceful shutdown

func (*WebApp) Shutdown

func (app *WebApp) Shutdown() error

Shutdown đóng HTTP server một cách an toàn, chờ các kết nối hiện tại kết thúc. Phương thức này nên được gọi khi muốn dừng server một cách graceful.

Returns:

  • error: Lỗi nếu có trong quá trình đóng server

func (*WebApp) Static

func (app *WebApp) Static(prefix, root string)

Static đăng ký một thư mục để phục vụ static files. Files trong thư mục này sẽ được phục vụ tại đường dẫn có tiền tố được chỉ định.

Parameters:

  • prefix: Tiền tố URL để phục vụ static files
  • root: Đường dẫn tới thư mục chứa static files

func (*WebApp) TrackConnection

func (app *WebApp) TrackConnection()

TrackConnection tăng số lượng active connections

func (*WebApp) UntrackConnection

func (app *WebApp) UntrackConnection()

UntrackConnection giảm số lượng active connections

func (*WebApp) Use

func (app *WebApp) Use(middleware ...router.HandlerFunc)

Use thêm một hoặc nhiều middleware vào WebApp. Middleware sẽ được thực thi theo thứ tự đăng ký cho mỗi request.

Parameters:

  • middleware: Danh sách các middleware functions cần thêm

type WebAppConfig

type WebAppConfig struct {
	// GracefulShutdown cấu hình graceful shutdown
	GracefulShutdown GracefulShutdownConfig `mapstructure:"graceful_shutdown" yaml:"graceful_shutdown"`
}

WebAppConfig chứa các cấu hình bảo mật và hiệu suất cho WebApp Note: Some configurations have been moved to dedicated middleware packages: - MaxRequestBodySize -> bodylimit middleware - AllowedMethods -> method middleware - RequestTimeout -> timeout middleware - EnableSecurityHeaders -> helmet middleware

func DefaultWebAppConfig

func DefaultWebAppConfig() *WebAppConfig

DefaultWebAppConfig trả về cấu hình mặc định cho WebApp Note: Middleware-specific configurations are now handled by their respective packages

func (*WebAppConfig) MergeConfig

func (c *WebAppConfig) MergeConfig(other *WebAppConfig)

MergeConfig hợp nhất cấu hình từ nhiều nguồn Note: Most configurations are now handled by middleware packages

func (*WebAppConfig) Validate

func (c *WebAppConfig) Validate() error

Validate kiểm tra tính hợp lệ của cấu hình Note: Most validations are now handled by middleware packages

Directories

Path Synopsis
Package adapter cung cấp interface và implementations cho việc kết nối framework với các HTTP server khác nhau (như net/http standard, fasthttp, v.v.).
Package adapter cung cấp interface và implementations cho việc kết nối framework với các HTTP server khác nhau (như net/http standard, fasthttp, v.v.).
Package mocks provides mock implementations for the http context interfaces.
Package mocks provides mock implementations for the http context interfaces.

Jump to

Keyboard shortcuts

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