{"id":50965022,"url":"https://github.com/kasidit-wansudon/go-api-gateway","last_synced_at":"2026-06-18T19:01:23.369Z","repository":{"id":362302331,"uuid":"1179977220","full_name":"kasidit-wansudon/go-api-gateway","owner":"kasidit-wansudon","description":"High-performance API Gateway \u0026 Rate Limiter built in Go. Features: reverse proxy, token bucket rate limiting, JWT auth, circuit breaker, Prometheus metrics, plugin system.","archived":false,"fork":false,"pushed_at":"2026-03-12T15:28:19.000Z","size":34,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-03T15:12:47.508Z","etag":null,"topics":["api-gateway","circuit-breaker","go","jwt","microservices","prometheus","rate-limiting"],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/kasidit-wansudon.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-12T15:17:28.000Z","updated_at":"2026-04-08T21:01:51.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/kasidit-wansudon/go-api-gateway","commit_stats":null,"previous_names":["kasidit-wansudon/go-api-gateway"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/kasidit-wansudon/go-api-gateway","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kasidit-wansudon%2Fgo-api-gateway","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kasidit-wansudon%2Fgo-api-gateway/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kasidit-wansudon%2Fgo-api-gateway/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kasidit-wansudon%2Fgo-api-gateway/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kasidit-wansudon","download_url":"https://codeload.github.com/kasidit-wansudon/go-api-gateway/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kasidit-wansudon%2Fgo-api-gateway/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34503511,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-18T02:00:06.871Z","response_time":128,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api-gateway","circuit-breaker","go","jwt","microservices","prometheus","rate-limiting"],"created_at":"2026-06-18T19:01:21.629Z","updated_at":"2026-06-18T19:01:23.344Z","avatar_url":"https://github.com/kasidit-wansudon.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cdiv align=\"center\"\u003e\n\n# 🚀 Go API Gateway\n\n**High-performance API Gateway \u0026 Rate Limiter built in Go**\n\n[![Go Version](https://img.shields.io/badge/Go-1.22+-00ADD8?style=for-the-badge\u0026logo=go\u0026logoColor=white)](https://go.dev/)\n[![Build Status](https://img.shields.io/github/actions/workflow/status/kasidit-wansudon/go-api-gateway/ci.yml?branch=main\u0026style=for-the-badge\u0026logo=github)](https://github.com/kasidit-wansudon/go-api-gateway/actions)\n[![Coverage](https://img.shields.io/codecov/c/github/kasidit-wansudon/go-api-gateway?style=for-the-badge\u0026logo=codecov)](https://codecov.io/gh/kasidit-wansudon/go-api-gateway)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=for-the-badge)](LICENSE)\n[![Go Report Card](https://goreportcard.com/badge/github.com/kasidit-wansudon/go-api-gateway?style=for-the-badge)](https://goreportcard.com/report/github.com/kasidit-wansudon/go-api-gateway)\n\n*A production-ready API gateway featuring dynamic routing, token bucket rate limiting, JWT authentication, circuit breakers, and Prometheus metrics — designed for cloud-native microservice architectures.*\n\n\u003c/div\u003e\n\n---\n\n## Architecture\n\n```\n                          ┌─────────────────────────────────────────────────────┐\n                          │                  Go API Gateway                      │\n                          │                                                     │\n    Clients               │  ┌──────────┐  ┌──────────┐  ┌────────────────┐    │     Upstreams\n   ─────────►  :8080  ────┼──┤ Request  ├──┤  Auth    ├──┤  Rate Limiter  ├──┐ │\n                          │  │   ID     │  │  (JWT)   │  │ (Token Bucket) │  │ │\n                          │  └──────────┘  └──────────┘  └────────────────┘  │ │\n                          │                                                   │ │  ┌──────────────┐\n                          │  ┌──────────┐  ┌──────────┐  ┌────────────────┐  │ ├──► User Service │\n                          │  │  CORS    │  │ Logging  │  │   Recovery     │  │ │  └──────────────┘\n                          │  │          │  │(zerolog) │  │  (panic safe)  │  │ │  ┌──────────────┐\n                          │  └──────────┘  └──────────┘  └────────────────┘  │ ├──► Product Svc  │\n                          │                                                   │ │  └──────────────┘\n                          │  ┌──────────────────────────────────────────────┐ │ │  ┌──────────────┐\n                          │  │          Reverse Proxy Router                │◄┘ └──► Order Svc   │\n                          │  │  (path-based routing, prefix strip, LPM)    │   │  └──────────────┘\n                          │  └─────────────────┬───────────────────────────┘   │\n                          │                    │                               │\n                          │          ┌─────────┴─────────┐                     │\n                          │          │  Circuit Breaker   │                     │\n                          │          │  (per upstream)    │                     │\n                          │          └───────────────────┘                     │\n                          └─────────────────────────────────────────────────────┘\n                                  │              │               │\n                              :9090          :9091           :6379\n                            Prometheus     Admin API         Redis\n                             Metrics       (routes,        (rate limit\n                                          config)          storage)\n```\n\n## Features\n\n- [x] **Reverse Proxy** — Dynamic path-based routing with longest-prefix matching\n- [x] **Rate Limiting** — Token bucket algorithm with per-client tracking\n- [x] **JWT Authentication** — HMAC-SHA256 token validation middleware\n- [x] **Circuit Breaker** — Protects upstreams with open/half-open/closed states\n- [x] **Middleware Chain** — Request ID, CORS, logging, panic recovery, metrics\n- [x] **Admin REST API** — Runtime route management, config reload, health checks\n- [x] **Prometheus Metrics** — Request count, latency histograms, error rates\n- [x] **Structured Logging** — JSON-formatted logs via zerolog\n- [x] **Graceful Shutdown** — Clean connection draining on SIGINT/SIGTERM\n- [x] **Hot Config Reload** — Update routes without restarting the gateway\n- [x] **Health Checks** — `/health` and `/ready` endpoints for orchestrators\n- [x] **Docker Ready** — Multi-stage build producing ~15MB scratch image\n- [ ] **Sliding Window Rate Limiting** — Redis-backed distributed limiting (planned)\n- [ ] **Plugin System** — Custom middleware via Go plugins (planned)\n- [ ] **Request/Response Transformation** — Header/body manipulation (planned)\n\n## Quick Start\n\n### Docker Compose (recommended)\n\n```bash\ngit clone https://github.com/kasidit-wansudon/go-api-gateway.git\ncd go-api-gateway\n\n# Start gateway + Redis + PostgreSQL + Prometheus + Grafana\ndocker compose -f deployments/docker-compose.yml up -d\n\n# Verify health\ncurl http://localhost:9091/health\n# {\"service\":\"go-api-gateway\",\"status\":\"healthy\"}\n```\n\n**Service endpoints after startup:**\n\n| Service    | URL                          | Description           |\n|------------|------------------------------|-----------------------|\n| Gateway    | `http://localhost:8080`      | Proxy endpoint        |\n| Admin API  | `http://localhost:9091`      | Route management      |\n| Metrics    | `http://localhost:9090`      | Prometheus metrics    |\n| Prometheus | `http://localhost:9092`      | Prometheus UI         |\n| Grafana    | `http://localhost:3000`      | Dashboards (admin/admin) |\n| Redis      | `localhost:6379`             | Rate limit storage    |\n| PostgreSQL | `localhost:5432`             | API key management    |\n\n### Build from Source\n\n```bash\n# Prerequisites: Go 1.22+\nmake build\n./bin/gateway --config configs/gateway.yaml\n```\n\n## Configuration Reference\n\nConfiguration is loaded from YAML with environment variable overrides (prefix: `GATEWAY_`).\n\n```yaml\nserver:\n  host: 0.0.0.0\n  port: 8080\n  read_timeout: 15s\n  write_timeout: 15s\n  idle_timeout: 60s\n  shutdown_timeout: 30s\n\nlogging:\n  level: info        # debug | info | warn | error\n  format: json       # json | console\n\nredis:\n  host: localhost\n  port: 6379\n  password: \"\"\n  db: 0\n\nauth:\n  jwt_secret: your-secret-key    # Override: GATEWAY_AUTH_JWT_SECRET\n  jwt_issuer: go-api-gateway\n  token_expiry: 24h\n\nmetrics:\n  enabled: true\n  path: /metrics\n  port: 9090\n\nadmin:\n  enabled: true\n  port: 9091\n  api_key: admin-secret-key      # Override: GATEWAY_ADMIN_API_KEY\n\nroutes:\n  - path: /api/v1/users\n    upstream: http://user-service:8001\n    methods: [GET, POST, PUT, DELETE]\n    strip_prefix: true\n    auth_required: true\n    timeout: 10s\n    rate_limit:\n      enabled: true\n      rate: 100          # requests per window\n      burst: 20          # max burst\n      window: 1m\n    circuit_breaker:\n      enabled: true\n      max_failures: 5\n      timeout: 30s\n      reset_timeout: 60s\n```\n\n### Environment Variable Overrides\n\nAll config values can be overridden via environment variables with the `GATEWAY_` prefix:\n\n```bash\nexport GATEWAY_SERVER_PORT=9000\nexport GATEWAY_AUTH_JWT_SECRET=production-secret\nexport GATEWAY_REDIS_HOST=redis.internal\nexport GATEWAY_LOGGING_LEVEL=debug\n```\n\n## Admin API\n\nThe admin API runs on a separate port (default: `9091`) and requires an API key for authenticated endpoints.\n\n### Endpoints\n\n```\nGET    /health                         # Public health check\nGET    /api/v1/health                  # Authenticated health check\nGET    /api/v1/ready                   # Readiness probe\nGET    /api/v1/routes                  # List all routes\nPOST   /api/v1/routes                  # Add a route\nDELETE /api/v1/routes/{path}           # Remove a route\nPOST   /api/v1/config/reload           # Hot-reload configuration\n```\n\n### Examples\n\n```bash\n# List all registered routes\ncurl -H \"X-API-Key: admin-secret-key\" http://localhost:9091/api/v1/routes\n\n# Add a new route at runtime\ncurl -X POST http://localhost:9091/api/v1/routes \\\n  -H \"X-API-Key: admin-secret-key\" \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"path\": \"/api/v1/payments\",\n    \"upstream\": \"http://payment-service:8004\",\n    \"methods\": [\"GET\", \"POST\"],\n    \"strip_prefix\": true\n  }'\n\n# Reload configuration from disk\ncurl -X POST -H \"X-API-Key: admin-secret-key\" \\\n  http://localhost:9091/api/v1/config/reload\n```\n\n## Metrics\n\nWhen metrics are enabled, the gateway exposes Prometheus-compatible metrics at `:9090/metrics`:\n\n| Metric                                  | Type      | Description                              |\n|-----------------------------------------|-----------|------------------------------------------|\n| `gateway_http_requests_total`           | Counter   | Total HTTP requests by method/path/status |\n| `gateway_http_request_duration_seconds` | Histogram | Request latency distribution              |\n| `gateway_http_active_requests`          | Gauge     | Currently in-flight requests              |\n| `gateway_upstream_errors_total`         | Counter   | Upstream error count by type              |\n| `gateway_circuit_breaker_state`         | Gauge     | Circuit state (0=closed, 1=open, 2=half) |\n\n## Project Structure\n\n```\ngo-api-gateway/\n├── cmd/gateway/\n│   └── main.go              # Entry point, server lifecycle, graceful shutdown\n├── internal/\n│   ├── config/              # YAML config loader with Viper, hot-reload\n│   ├── proxy/               # Reverse proxy with dynamic routing (LPM)\n│   ├── ratelimit/           # Token bucket rate limiter (in-memory)\n│   ├── auth/                # JWT validation, claims context, middleware\n│   ├── circuit/             # Circuit breaker (closed → open → half-open)\n│   ├── middleware/          # Request ID, CORS, logging, recovery, metrics\n│   ├── admin/               # Admin REST API (gorilla/mux)\n│   └── metrics/             # Prometheus metric recording\n├── pkg/cache/               # Redis client wrapper\n├── configs/\n│   └── gateway.yaml         # Sample configuration\n├── deployments/\n│   ├── Dockerfile           # Multi-stage scratch build\n│   ├── docker-compose.yml   # Full stack (gateway + redis + postgres + prometheus + grafana)\n│   └── prometheus.yml       # Prometheus scrape config\n├── .github/workflows/\n│   └── ci.yml               # Lint → Test → Build → Docker\n├── Makefile                 # build, test, lint, docker, run targets\n├── go.mod\n└── README.md\n```\n\n## Development\n\n```bash\n# Run all tests\nmake test\n\n# Run tests with coverage report\nmake test-cover\n\n# Run benchmarks\nmake bench\n\n# Format and vet\nmake lint\n\n# Build and run locally\nmake run\n\n# Build Docker image\nmake docker\n```\n\n## Benchmarks\n\n\u003e Benchmarked on Apple M2 Pro / Go 1.22 / Linux\n\n| Component        | Operation       | ops/sec       | ns/op  | allocs/op |\n|------------------|-----------------|---------------|--------|-----------|\n| Token Bucket     | Allow (single)  | 30,000,000+   | ~33    | 0         |\n| Token Bucket     | Allow (parallel)| 10,000,000+   | ~100   | 0         |\n| Circuit Breaker  | Execute (closed)| 50,000,000+   | ~20    | 0         |\n| Reverse Proxy    | Route lookup    | 20,000,000+   | ~50    | 0         |\n\n**Target production performance:**\n- **10,000+ RPS** with \u003c 5ms p99 latency\n- **Zero-downtime** configuration reload\n- **90%+ test coverage** on core packages\n\n## Tech Stack\n\n| Technology        | Purpose                           |\n|-------------------|-----------------------------------|\n| **Go 1.22+**      | Core language (net/http, goroutines) |\n| **Redis**          | Rate limiting, caching            |\n| **PostgreSQL**     | API key management, analytics     |\n| **Prometheus**     | Metrics collection                |\n| **Grafana**        | Monitoring dashboards             |\n| **Docker**         | Containerization                  |\n| **GitHub Actions** | CI/CD pipeline                    |\n| **zerolog**        | Structured JSON logging           |\n| **Viper**          | Configuration management          |\n| **gorilla/mux**    | Admin API routing                 |\n\n## Contributing\n\nContributions are welcome! Please follow these steps:\n\n1. Fork the repository\n2. Create a feature branch (`git checkout -b feature/amazing-feature`)\n3. Write tests for your changes\n4. Ensure all tests pass (`make test`)\n5. Run linting (`make lint`)\n6. Commit your changes (`git commit -m 'Add amazing feature'`)\n7. Push to the branch (`git push origin feature/amazing-feature`)\n8. Open a Pull Request\n\n### Code Style\n\n- Follow standard Go conventions ([Effective Go](https://go.dev/doc/effective_go))\n- Use `go fmt` and `go vet` before committing\n- Write table-driven tests where appropriate\n- Keep functions focused and under 50 lines when possible\n\n## License\n\nThis project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.\n\n---\n\n\u003cdiv align=\"center\"\u003e\n\n**Built with ❤️ by [Kasidit Wansudon](https://github.com/kasidit-wansudon)**\n\n\u003c/div\u003e\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkasidit-wansudon%2Fgo-api-gateway","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkasidit-wansudon%2Fgo-api-gateway","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkasidit-wansudon%2Fgo-api-gateway/lists"}