← MySQL | Imaging →

API Gateway - Go API 网关

API Gateway 是微服务架构的入口点,负责请求路由、认证、限流等功能。使用 Go 构建 API Gateway 可以利用其高并发优势。

网关基础

📝 基础网关实现

package main

import (
    "fmt"
    "net/http"
    "net/http/httputil"
    "net/url"
)

type Gateway struct {
    proxies map[string]*httputil.ReverseProxy
}

func NewGateway() *Gateway {
    g := &Gateway{
        proxies: make(map[string]*httputil.ReverseProxy),
    }
    
    // 注册服务
    g.Register("/user-service", "http://localhost:8081")
    g.Register("/order-service", "http://localhost:8082")
    
    return g
}

func (g *Gateway) Register(path, target string) {
    targetURL, _ := url.Parse(target)
    g.proxies[path] = httputil.NewSingleHostReverseProxy(targetURL)
}

func (g *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    // 路由匹配
    for path, proxy := range g.proxies {
        if len(r.URL.Path) > len(path) && r.URL.Path[:len(path)] == path {
            // 认证检查
            if !g.authenticate(r) {
                http.Error(w, "Unauthorized", http.StatusUnauthorized)
                return
            }
            
            // 转发请求
            proxy.ServeHTTP(w, r)
            return
        }
    }
    
    http.NotFound(w, r)
}

func (g *Gateway) authenticate(r *http.Request) bool {
    token := r.Header.Get("Authorization")
    return token != ""
}

func main() {
    gateway := NewGateway()
    http.ListenAndServe(":8080", gateway)
}

中间件

📝 网关中间件

// 限流中间件
func RateLimit(middleware http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // 实现限流逻辑
        middleware.ServeHTTP(w, r)
    })
}

// 日志中间件
func Logging(middleware http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        middleware.ServeHTTP(w, r)
        fmt.Printf("[%s] %s %v\n", r.Method, r.URL.Path, time.Since(start))
    })
}

// CORS 中间件
func CORS(middleware http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
        
        if r.Method == "OPTIONS" {
            w.WriteHeader(http.StatusNoContent)
            return
        }
        
        middleware.ServeHTTP(w, r)
    })
}

📖 延伸阅读