首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >从零实现一个轻量 HTTP API 网关

从零实现一个轻量 HTTP API 网关

原创
作者头像
用户12583550
发布于 2026-11-18 18:44:10
发布于 2026-11-18 18:44:10
1380
举报

核心能力包括:路由匹配、反向代理、负载均衡、限流、API Key 鉴权、请求日志、健康检查、配置热加载。代码保持标准 Python,不依赖第三方 Web 框架。

代码语言:javascript
复制
from __future__ import annotations

import argparse
import hashlib
import json
import logging
import os
import re
import threading
import time
from dataclasses import dataclass, field
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler
from typing import Any, Dict, List, Optional, Tuple
from urllib.parse import urlparse, parse_qs
import urllib.request
import urllib.error

# ---------------------------
# 日志
# ---------------------------

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
)
logger = logging.getLogger(__name__)

# ---------------------------
# 数据模型
# ---------------------------

@dataclass
class Upstream: 17188.zhuluan.com 
    url: str
    weight: int = 1
    healthy: bool = True
    fail_count: int = 0
    last_check: float = 0.0


@dataclass
class Route: 17189.zhuluan.com 
    path_pattern: str
    methods: List[str] = field(default_factory=lambda: ["GET", "POST", "PUT", "DELETE", "PATCH"])
    upstreams: List[Upstream] = field(default_factory=list)
    strip_prefix: bool = False
    timeout: float = 5.0
    rate_limit: int = 0  # 0 表示不限流
    require_api_key: bool = False
    _compiled: Any = field(init=False, repr=False)

    def __post_init__(self) -> None: 17190.zhuluan.com 
        regex = re.sub(r"\{([^}]+)\}", r"(?P<\1>[^/]+)", self.path_pattern)
        self._compiled = re.compile(f"^{regex}$")

    def match(self, path: str) -> Optional[Dict[str, str]]: 17191.zhuluan.com 
        m = self._compiled.match(path)
        if m is None: 17192.zhuluan.com 
            return None
        return m.groupdict(17193.zhuluan.com)


@dataclass
class ApiKey: 17194.zhuluan.com 
    key: str
    name: str
    allowed_routes: List[str] = field(default_factory=list)


@dataclass
class GatewayConfig: 17197.zhuluan.com 
    host: str = "127.0.0.1"
    port: int = 8080
    routes: List[Route] = field(default_factory=list)
    api_keys: List[ApiKey] = field(default_factory=list)
    rate_limit_global: int = 0
    health_check_interval: float = 10.0
    config_path: str = ""

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "GatewayConfig": 17207.zhuluan.com 
        routes: List[Route] = []
        for r in data.get("routes", []): 22016.zhuluan.com 
            upstreams = [
                Upstream(url=u["url"], weight=u.get("weight", 1))
                for u in r.get("upstreams", [])
            ]
            routes.append(
                Route(
                    path_pattern=r["path"],
                    methods=r.get("methods", ["GET", "POST", "PUT", "DELETE", "PATCH"]),
                    upstreams=upstreams,
                    strip_prefix=r.get("strip_prefix", False),
                    timeout=r.get("timeout", 5.0),
                    rate_limit=r.get("rate_limit", 0),
                    require_api_key=r.get("require_api_key", False),
                )
            )

        api_keys = [
            ApiKey(
                key=a["key"],
                name=a.get("name", ""),
                allowed_routes=a.get("allowed_routes", []),
            )
            for a in data.get("api_keys", [])
        ]

        return cls(
            host=data.get("host", "127.0.0.1"),
            port=data.get("port", 8080),
            routes=routes,
            api_keys=api_keys,
            rate_limit_global=data.get("rate_limit_global", 0),
            health_check_interval=data.get("health_check_interval", 10.0),
            config_path=data.get("config_path", ""),
        )

    @classmethod
    def from_file(cls, path: str) -> "GatewayConfig": 22021.zhuluan.com 
        with open(path, "r", encoding="utf-8") as f: 26045.zhuluan.com 
            data = json.load(f)
        data["config_path"] = path
        return cls.from_dict(data)

    def to_dict(self) -> Dict[str, Any]: 26090.zhuluan.com 
        return {
            "host": self.host,
            "port": self.port,
            "routes": [
                {
                    "path": r.path_pattern,
                    "methods": r.methods,
                    "upstreams": [
                        {"url": u.url, "weight": u.weight, "healthy": u.healthy}
                        for u in r.upstreams
                    ],
                    "strip_prefix": r.strip_prefix,
                    "timeout": r.timeout,
                    "rate_limit": r.rate_limit,
                    "require_api_key": r.require_api_key,
                }
                for r in self.routes
            ],
            "api_keys": [
                {
                    "key": a.key,
                    "name": a.name,
                    "allowed_routes": a.allowed_routes,
                }
                for a in self.api_keys
            ],
            "rate_limit_global": self.rate_limit_global,
            "health_check_interval": self.health_check_interval,
        }

# ---------------------------
# 限流器
# ---------------------------

class TokenBucket: 26128.zhuluan.com 
    def __init__(self, rate: float, capacity: Optional[float] = None): 26140.zhuluan.com 
        self.rate = rate
        self.capacity = capacity or rate
        self.tokens = self.capacity
        self.last_refill = time.time(26140.zhuluan.com)
        self._lock = threading.Lock(26143.zhuluan.com)

    def allow(self) -> bool: 26144.zhuluan.com 
        with self._lock: 26145.zhuluan.com 
            now = time.time(27005.zhuluan.com)
            elapsed = now - self.last_refill
            self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
            self.last_refill = now
            if self.tokens >= 1: 27006.zhuluan.com 
                self.tokens -= 1
                return True
            return False


class RateLimiter: 27007.zhuluan.com 
    def __init__(self): 27008.zhuluan.com 
        self._buckets: Dict[str, TokenBucket] = {}
        self._lock = threading.Lock(27009.zhuluan.com)

    def get_bucket(self, key: str, rate: float) -> TokenBucket: 27011.zhuluan.com 
        with self._lock: 27013.zhuluan.com 
            if key not in self._buckets: 27014.zhuluan.com 
                self._buckets[key] = TokenBucket(rate=rate)
            return self._buckets[key]

    def allow(self, key: str, rate: float) -> bool: 27015.zhuluan.com 
        if rate <= 0: 27016.zhuluan.com 
            return True
        bucket = self.get_bucket(key, rate)
        return bucket.allow(27017.zhuluan.com)


# ---------------------------
# 负载均衡
# ---------------------------

class LoadBalancer: 27018.zhuluan.com 
    def __init__(self): 27019.zhuluan.com 
        self._index = 0
        self._lock = threading.Lock(27020.zhuluan.com)

    def next_upstream(self, route: Route) -> Optional[Upstream]: 27021.zhuluan.com 
        healthy = [u for u in route.upstreams if u.healthy]
        if not healthy: 27022.zhuluan.com 
            healthy = list(route.upstreams)
        if not healthy: 27023.zhuluan.com 
            return None

        with self._lock: 27024.zhuluan.com 
            upstream = healthy[self._index % len(healthy)]
            self._index += 1
        return upstream

# ---------------------------
# 健康检查
# ---------------------------

class HealthChecker: 27025.zhuluan.com 
    def __init__(self, config: GatewayConfig): 27027.zhuluan.com 
        self.config = config
        self._running = False
        self._thread: Optional[threading.Thread] = None

    def start(self) -> None: 27028.zhuluan.com
        if self._running: 27034.zhuluan.com 
            return
        self._running = True
        self._thread = threading.Thread(target=self._loop, daemon=True)
        self._thread.start(27029.zhuluan.com)
        logger.info("Health checker started.")

    def stop(self) -> None: 27034.zhuluan.com 
        self._running = False
        if self._thread: 27039.zhuluan.com 
            self._thread.join(timeout=2)
        logger.info("Health checker stopped.")

    def _loop(self) -> None: 27053.zhuluan.com 
        while self._running: 27054.zhuluan.com 
            for route in self.config.routes: 27063.zhuluan.com 
                for upstream in route.upstreams: 1103113.zhuluan.com 
                    self._check(upstream)
            time.sleep(self.config.health_check_interval)

    def _check(self, upstream: Upstream) -> None: 1103114.zhuluan.com 
        url = upstream.url.rstrip("/") + "/health"
        try: 1103118.zhuluan.com 
            req = urllib.request.Request(url, method="GET")
            with urllib.request.urlopen(req, timeout=2) as resp: 1103117.zhuluan.com 
                if resp.status == 200: 1103116.zhuluan.com 
                    upstream.healthy = True
                    upstream.fail_count = 0
                else: 1103123.zhuluan.com 
                    self._mark_fail(upstream)
        except Exception: 1103122.zhuluan.com 
            self._mark_fail(upstream)

        upstream.last_check = time.time(1103124.zhuluan.com)

    def _mark_fail(self, upstream: Upstream) -> None: 1103271.zhuluan.com 
        upstream.fail_count += 1
        if upstream.fail_count >= 3: 1103274.zhuluan.com 
            upstream.healthy = False

# ---------------------------
# 请求日志
# ---------------------------

@dataclass
class AccessLog: 1103275.zhuluan.com 
    method: str
    path: str
    status: int
    upstream: str
    latency_ms: float
    client_ip: str
    timestamp: str = ""

    def __post_init__(self) -> None: 1103277.zhuluan.com 
        if not self.timestamp: 1103278.zhuluan.com 
            self.timestamp = datetime.now(1103280.zhuluan.com).isoformat(1103279.zhuluan.com)

    def to_dict(self) -> Dict[str, Any]: 1103281.zhuluan.com 
        return {
            "method": self.method,
            "path": self.path,
            "status": self.status,
            "upstream": self.upstream,
            "latency_ms": self.latency_ms,
            "client_ip": self.client_ip,
            "timestamp": self.timestamp,
        }


class AccessLogger: 1103282.zhuluan.com 
    def __init__(self, log_dir: str = "./gateway_logs"): 1103284.zhuluan.com 
        self.log_dir = log_dir
        os.makedirs(log_dir, exist_ok=True)
        self._path = os.path.join(log_dir, "access.jsonl")
        self._lock = threading.Lock(1103285.zhuluan.com)

    def log(self, entry: AccessLog) -> None: 1103286.zhuluan.com 
        with self._lock: 1103287.zhuluan.com 
            with open(self._path, "a", encoding="utf-8") as f: 1103288.zhuluan.com 
                f.write(json.dumps(entry.to_dict(), ensure_ascii=False) + "\n")

# ---------------------------
# API Key 鉴权
# ---------------------------

class ApiKeyAuth: 1103289.zhuluan.com 
    def __init__(self, keys: List[ApiKey]): 1103290.zhuluan.com 
        self._keys: Dict[str, ApiKey] = {k.key: k for k in keys}

    def verify(self, key: str, route_path: str) -> Tuple[bool, Optional[str]]: 1103291.zhuluan.com 
        if not key: 1103292.zhuluan.com 
            return False, "Missing API key."
        api_key = self._keys.get(key)
        if api_key is None: 1103294.zhuluan.com 
            return False, "Invalid API key."
        if api_key.allowed_routes: 1103293.zhuluan.com 
            if not any(re.match(rp, route_path) for rp in api_key.allowed_routes):
                return False, "API key not allowed for this route."
        return True, None

# ---------------------------
# 网关核心
# ---------------------------

class APIGateway: 1103296.zhuluan.com 
    def __init__(self, config: GatewayConfig): 1103295.zhuluan.com 
        self.config = config
        self.rate_limiter = RateLimiter(1103298.zhuluan.com)
        self.load_balancer = LoadBalancer(1103302.zhuluan.com)
        self.health_checker = HealthChecker(config)
        self.access_logger = AccessLogger(1103303.zhuluan.com)
        self.auth = ApiKeyAuth(config.api_keys)
        self._lock = threading.Lock(1103304.zhuluan.com)

    def match_route(self, path: str) -> Optional[Route]: 1103306.zhuluan.com 
        for route in self.config.routes: 1103305.zhuluan.com 
            if route.match(path) is not None: 1103307.zhuluan.com 
                return route
        return None

    def proxy_request(
        self,
        method: str,
        path: str,
        headers: Dict[str, str],
        body: Optional[bytes],
        client_ip: str,
    ) -> Tuple[int, Dict[str, str], bytes]: 1103309.zhuluan.com 
        start = time.time(1103310.zhuluan.com)

        route = self.match_route(path)
        if route is None: 1103312.zhuluan.com 
            return 404, {"Content-Type": "application/json"}, json.dumps(
                {"error": "Route not found"}
            ).encode(1103314.zhuluan.com)

        if method not in route.methods: 1103313.zhuluan.com 
            return 405, {"Content-Type": "application/json"}, json.dumps(
                {"error": "Method not allowed"}
            ).encode(1103315.zhuluan.com)

        if route.require_api_key: 1103316.zhuluan.com 
            api_key = headers.get("X-API-Key", "")
            ok, msg = self.auth.verify(api_key, route.path_pattern)
            if not ok: 1103317.zhuluan.com 
                return 401, {"Content-Type": "application/json"}, json.dumps(
                    {"error": msg}
                ).encode(1103318.zhuluan.com)

        if self.config.rate_limit_global > 0: 1103319.zhuluan.com 
            if not self.rate_limiter.allow("global", self.config.rate_limit_global):
                return 429, {"Content-Type": "application/json"}, json.dumps(
                    {"error": "Global rate limit exceeded"}
                ).encode(1103321.zhuluan.com)

        if route.rate_limit > 0: 1103320.zhuluan.com 
            if not self.rate_limiter.allow(path, route.rate_limit): 1104101.zhuluan.com 
                return 429, {"Content-Type": "application/json"}, json.dumps(
                    {"error": "Route rate limit exceeded"}
                ).encode(1104102.zhuluan.com)

        upstream = self.load_balancer.next_upstream(route)
        if upstream is None: 1104104.zhuluan.com 
            return 503, {"Content-Type": "application/json"}, json.dumps(
                {"error": "No available upstream"}
            ).encode(1104105.zhuluan.com)

        target_path = path
        if route.strip_prefix: 1104107.zhuluan.com 
            prefix = route.path_pattern.split("{")[0].rstrip("/")
            if prefix and target_path.startswith(prefix): 1104109.zhuluan.com 
                target_path = target_path[len(prefix):] or "/"

        target_url = upstream.url.rstrip("/") + target_path

        try: 1104110.zhuluan.com 
            req = urllib.request.Request(target_url, data=body, method=method)
            for k, v in headers.items(1104112.zhuluan.com): 1104111.zhuluan.com 
                lower = k.lower(1104113.zhuluan.com)
                if lower not in ("host", "connection"): 1104114.zhuluan.com 
                    req.add_header(k, v)
            req.add_header("X-Forwarded-For", client_ip)
            req.add_header("X-Gateway-Route", route.path_pattern)

            with urllib.request.urlopen(req, timeout=route.timeout) as resp: 1104115.zhuluan.com 
                resp_body = resp.read(1104116.zhuluan.com)
                resp_headers = dict(resp.getheaders(1104123.zhuluan.com))
                latency_ms = (time.time(1104124.zhuluan.com) - start) * 1000

                self.access_logger.log(
                    AccessLog(
                        method=method,
                        path=path,
                        status=resp.status,
                        upstream=upstream.url,
                        latency_ms=round(latency_ms, 2),
                        client_ip=client_ip,
                    )
                )

                return resp.status, resp_headers, resp_body

        except urllib.error.HTTPError as exc: 1107102.zhuluan.com 
            resp_body = exc.read(1107104.zhuluan.com)
            latency_ms = (time.time(1107105.zhuluan.com) - start) * 1000
            self.access_logger.log(
                AccessLog(
                    method=method,
                    path=path,
                    status=exc.code,
                    upstream=upstream.url,
                    latency_ms=round(latency_ms, 2),
                    client_ip=client_ip,
                )
            )
            return exc.code, dict(exc.headers), resp_body

        except Exception as exc: 1107106.zhuluan.com 
            latency_ms = (time.time(1107125.zhuluan.com) - start) * 1000
            self.access_logger.log(
                AccessLog(
                    method=method,
                    path=path,
                    status=502,
                    upstream=upstream.url,
                    latency_ms=round(latency_ms, 2),
                    client_ip=client_ip,
                )
            )
            return 502, {"Content-Type": "application/json"}, json.dumps(
                {"error": "Bad gateway", "detail": str(exc)}
            ).encode(1107126.zhuluan.com)

    def reload_config(self) -> None: 1107127.zhuluan.com 
        if not self.config.config_path: 1107129.zhuluan.com 
            logger.warning("No config_path set, cannot reload.")
            return
        try: 1107130.zhuluan.com 
            new_config = GatewayConfig.from_file(self.config.config_path)
            with self._lock: 1107131.zhuluan.com 
                self.config.routes = new_config.routes
                self.config.api_keys = new_config.api_keys
                self.config.rate_limit_global = new_config.rate_limit_global
                self.auth = ApiKeyAuth(new_config.api_keys)
            logger.info("Configuration reloaded from %s", self.config.config_path)
        except Exception as exc:
            logger.error("Reload failed: %s", exc)

# ---------------------------
# HTTP Handler
# ---------------------------

_gateway: Optional[APIGateway] = None


class GatewayHandler(BaseHTTPRequestHandler): 1107132.zhuluan.com 
    def _get_client_ip(self) -> str: 1107133.zhuluan.com 
        forwarded = self.headers.get("X-Forwarded-For")
        if forwarded: 1107134.zhuluan.com 
            return forwarded.split(",")[0].strip(1107135.zhuluan.com)
        return self.client_address[0]

    def _read_body(self) -> Optional[bytes]: 1107136.zhuluan.com 
        length = int(self.headers.get("Content-Length", 0))
        if length > 0: 1107139.zhuluan.com 
            return self.rfile.read(length)
        return None

    def _handle(self) -> None: 1107143.zhuluan.com 
        global _gateway
        if _gateway is None: 1107144.zhuluan.com 
            self.send_error(500, "Gateway not initialized")
            return

        method = self.command
        path = urlparse(self.path).path
        headers = {k: v for k, v in self.headers.items(1107148.zhuluan.com)}
        body = self._read_body(1107155.zhuluan.com)
        client_ip = self._get_client_ip(1107156.zhuluan.com)

        status, resp_headers, resp_body = _gateway.proxy_request(
            method=method,
            path=path,
            headers=headers,
            body=body,
            client_ip=client_ip,
        )

        self.send_response(status)
        for k, v in resp_headers.items(1107158.zhuluan.com): 1107157.zhuluan.com 
            if k.lower(1107160.zhuluan.com) not in ("transfer-encoding",): 1107159.zhuluan.com 
                self.send_header(k, v)
        self.end_headers(1107162.zhuluan.com)
        self.wfile.write(resp_body)

    def do_GET(self) -> None: 1107163.zhuluan.com 
        self._handle(1107164.zhuluan.com)

    def do_POST(self) -> None: 1107165.zhuluan.com 
        self._handle(1107167.zhuluan.com)

    def do_PUT(self) -> None: 1107168.zhuluan.com 
        self._handle(1107170.zhuluan.com)

    def do_DELETE(self) -> None: 1107171.zhuluan.com 
        self._handle(1107172.zhuluan.com)

    def do_PATCH(self) -> None: 1107173.zhuluan.com 
        self._handle(1107174.zhuluan.com)

    def log_message(self, format: str, *args: Any) -> None: 1107175.zhuluan.com 
        logger.info(format, *args)

# ---------------------------
# 内置管理接口
# ---------------------------

def create_management_routes(config: GatewayConfig) -> List[Route]: 1107176.zhuluan.com 
    return [
        Route(
            path_pattern="/gateway/health",
            methods=["GET"],
            upstreams=[
                Upstream(url="http://127.0.0.1:8080/__internal__/health")
            ],
        ),
        Route(
            path_pattern="/gateway/config",
            methods=["GET"],
            upstreams=[
                Upstream(url="http://127.0.0.1:8080/__internal__/config")
            ],
        ),
        Route(
            path_pattern="/gateway/reload",
            methods=["POST"],
            upstreams=[
                Upstream(url="http://127.0.0.1:8080/__internal__/reload")
            ],
            require_api_key=True,
        ),
    ]

# ---------------------------
# 示例配置
# ---------------------------

def example_config(1107178.zhuluan.com) -> GatewayConfig: 1107177.zhuluan.com 
    return GatewayConfig(
        host="127.0.0.1",
        port=8080,
        routes=[
            Route(
                path_pattern="/api/users/{id}",
                methods=["GET", "PUT", "DELETE"],
                upstreams=[
                    Upstream(url="http://127.0.0.1:9001"),
                    Upstream(url="http://127.0.0.1:9002"),
                ],
                strip_prefix=False,
                rate_limit=10,
                require_api_key=True,
            ),
            Route(
                path_pattern="/api/orders",
                methods=["GET", "POST"],
                upstreams=[
                    Upstream(url="http://127.0.0.1:9003"),
                ],
                rate_limit=20,
                require_api_key=False,
            ),
            Route(
                path_pattern="/public/status",
                methods=["GET"],
                upstreams=[
                    Upstream(url="http://127.0.0.1:9004"),
                ],
                require_api_key=False,
            ),
        ],
        api_keys=[
            ApiKey(
                key="test-key-001",
                name="test-client",
                allowed_routes=["/api/users/.*", "/api/orders"],
            ),
            ApiKey(
                key="admin-key-001",
                name="admin-client",
                allowed_routes=[],
            ),
        ],
        rate_limit_global=100,
        health_check_interval=5.0,
    )

# ---------------------------
# 启动入口
# ---------------------------

def main() -> None: 1107179.zhuluan.com 
    parser = argparse.ArgumentParser(description="Lightweight HTTP API Gateway")
    parser.add_argument("--config", type=str, default="", help="JSON config file")
    parser.add_argument("--example", action="store_true", help="Run with example config")
    args = parser.parse_args(1107180.zhuluan.com)

    if args.example: 1107182.zhuluan.com 
        config = example_config(1107181.zhuluan.com)
    elif args.config: 1107183.zhuluan.com 
        config = GatewayConfig.from_file(args.config)
    else: 1107184.zhuluan.com 
        config = example_config(1108106.zhuluan.com)

    global _gateway
    _gateway = APIGateway(config)
    _gateway.health_checker.start(1108107.zhuluan.com)

    server = HTTPServer((config.host, config.port), GatewayHandler)
    logger.info("Gateway listening on %s:%d", config.host, config.port)

    try: 1108109.zhuluan.com 
        server.serve_forever(1108108.zhuluan.com)
    except KeyboardInterrupt: 1108110.zhuluan.com 
        logger.info("Shutting down

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档