https://github.com/kasidit-wansudon/go-api-gateway
High-performance API Gateway & Rate Limiter built in Go. Features: reverse proxy, token bucket rate limiting, JWT auth, circuit breaker, Prometheus metrics, plugin system.
https://github.com/kasidit-wansudon/go-api-gateway
api-gateway circuit-breaker go jwt microservices prometheus rate-limiting
Last synced: 13 days ago
JSON representation
High-performance API Gateway & Rate Limiter built in Go. Features: reverse proxy, token bucket rate limiting, JWT auth, circuit breaker, Prometheus metrics, plugin system.
- Host: GitHub
- URL: https://github.com/kasidit-wansudon/go-api-gateway
- Owner: kasidit-wansudon
- License: mit
- Created: 2026-03-12T15:17:28.000Z (4 months ago)
- Default Branch: main
- Last Pushed: 2026-03-12T15:28:19.000Z (4 months ago)
- Last Synced: 2026-06-03T15:12:47.508Z (28 days ago)
- Topics: api-gateway, circuit-breaker, go, jwt, microservices, prometheus, rate-limiting
- Language: Go
- Size: 33.2 KB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# 🚀 Go API Gateway
**High-performance API Gateway & Rate Limiter built in Go**
[](https://go.dev/)
[](https://github.com/kasidit-wansudon/go-api-gateway/actions)
[](https://codecov.io/gh/kasidit-wansudon/go-api-gateway)
[](LICENSE)
[](https://goreportcard.com/report/github.com/kasidit-wansudon/go-api-gateway)
*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.*
---
## Architecture
```
┌─────────────────────────────────────────────────────┐
│ Go API Gateway │
│ │
Clients │ ┌──────────┐ ┌──────────┐ ┌────────────────┐ │ Upstreams
─────────► :8080 ────┼──┤ Request ├──┤ Auth ├──┤ Rate Limiter ├──┐ │
│ │ ID │ │ (JWT) │ │ (Token Bucket) │ │ │
│ └──────────┘ └──────────┘ └────────────────┘ │ │
│ │ │ ┌──────────────┐
│ ┌──────────┐ ┌──────────┐ ┌────────────────┐ │ ├──► User Service │
│ │ CORS │ │ Logging │ │ Recovery │ │ │ └──────────────┘
│ │ │ │(zerolog) │ │ (panic safe) │ │ │ ┌──────────────┐
│ └──────────┘ └──────────┘ └────────────────┘ │ ├──► Product Svc │
│ │ │ └──────────────┘
│ ┌──────────────────────────────────────────────┐ │ │ ┌──────────────┐
│ │ Reverse Proxy Router │◄┘ └──► Order Svc │
│ │ (path-based routing, prefix strip, LPM) │ │ └──────────────┘
│ └─────────────────┬───────────────────────────┘ │
│ │ │
│ ┌─────────┴─────────┐ │
│ │ Circuit Breaker │ │
│ │ (per upstream) │ │
│ └───────────────────┘ │
└─────────────────────────────────────────────────────┘
│ │ │
:9090 :9091 :6379
Prometheus Admin API Redis
Metrics (routes, (rate limit
config) storage)
```
## Features
- [x] **Reverse Proxy** — Dynamic path-based routing with longest-prefix matching
- [x] **Rate Limiting** — Token bucket algorithm with per-client tracking
- [x] **JWT Authentication** — HMAC-SHA256 token validation middleware
- [x] **Circuit Breaker** — Protects upstreams with open/half-open/closed states
- [x] **Middleware Chain** — Request ID, CORS, logging, panic recovery, metrics
- [x] **Admin REST API** — Runtime route management, config reload, health checks
- [x] **Prometheus Metrics** — Request count, latency histograms, error rates
- [x] **Structured Logging** — JSON-formatted logs via zerolog
- [x] **Graceful Shutdown** — Clean connection draining on SIGINT/SIGTERM
- [x] **Hot Config Reload** — Update routes without restarting the gateway
- [x] **Health Checks** — `/health` and `/ready` endpoints for orchestrators
- [x] **Docker Ready** — Multi-stage build producing ~15MB scratch image
- [ ] **Sliding Window Rate Limiting** — Redis-backed distributed limiting (planned)
- [ ] **Plugin System** — Custom middleware via Go plugins (planned)
- [ ] **Request/Response Transformation** — Header/body manipulation (planned)
## Quick Start
### Docker Compose (recommended)
```bash
git clone https://github.com/kasidit-wansudon/go-api-gateway.git
cd go-api-gateway
# Start gateway + Redis + PostgreSQL + Prometheus + Grafana
docker compose -f deployments/docker-compose.yml up -d
# Verify health
curl http://localhost:9091/health
# {"service":"go-api-gateway","status":"healthy"}
```
**Service endpoints after startup:**
| Service | URL | Description |
|------------|------------------------------|-----------------------|
| Gateway | `http://localhost:8080` | Proxy endpoint |
| Admin API | `http://localhost:9091` | Route management |
| Metrics | `http://localhost:9090` | Prometheus metrics |
| Prometheus | `http://localhost:9092` | Prometheus UI |
| Grafana | `http://localhost:3000` | Dashboards (admin/admin) |
| Redis | `localhost:6379` | Rate limit storage |
| PostgreSQL | `localhost:5432` | API key management |
### Build from Source
```bash
# Prerequisites: Go 1.22+
make build
./bin/gateway --config configs/gateway.yaml
```
## Configuration Reference
Configuration is loaded from YAML with environment variable overrides (prefix: `GATEWAY_`).
```yaml
server:
host: 0.0.0.0
port: 8080
read_timeout: 15s
write_timeout: 15s
idle_timeout: 60s
shutdown_timeout: 30s
logging:
level: info # debug | info | warn | error
format: json # json | console
redis:
host: localhost
port: 6379
password: ""
db: 0
auth:
jwt_secret: your-secret-key # Override: GATEWAY_AUTH_JWT_SECRET
jwt_issuer: go-api-gateway
token_expiry: 24h
metrics:
enabled: true
path: /metrics
port: 9090
admin:
enabled: true
port: 9091
api_key: admin-secret-key # Override: GATEWAY_ADMIN_API_KEY
routes:
- path: /api/v1/users
upstream: http://user-service:8001
methods: [GET, POST, PUT, DELETE]
strip_prefix: true
auth_required: true
timeout: 10s
rate_limit:
enabled: true
rate: 100 # requests per window
burst: 20 # max burst
window: 1m
circuit_breaker:
enabled: true
max_failures: 5
timeout: 30s
reset_timeout: 60s
```
### Environment Variable Overrides
All config values can be overridden via environment variables with the `GATEWAY_` prefix:
```bash
export GATEWAY_SERVER_PORT=9000
export GATEWAY_AUTH_JWT_SECRET=production-secret
export GATEWAY_REDIS_HOST=redis.internal
export GATEWAY_LOGGING_LEVEL=debug
```
## Admin API
The admin API runs on a separate port (default: `9091`) and requires an API key for authenticated endpoints.
### Endpoints
```
GET /health # Public health check
GET /api/v1/health # Authenticated health check
GET /api/v1/ready # Readiness probe
GET /api/v1/routes # List all routes
POST /api/v1/routes # Add a route
DELETE /api/v1/routes/{path} # Remove a route
POST /api/v1/config/reload # Hot-reload configuration
```
### Examples
```bash
# List all registered routes
curl -H "X-API-Key: admin-secret-key" http://localhost:9091/api/v1/routes
# Add a new route at runtime
curl -X POST http://localhost:9091/api/v1/routes \
-H "X-API-Key: admin-secret-key" \
-H "Content-Type: application/json" \
-d '{
"path": "/api/v1/payments",
"upstream": "http://payment-service:8004",
"methods": ["GET", "POST"],
"strip_prefix": true
}'
# Reload configuration from disk
curl -X POST -H "X-API-Key: admin-secret-key" \
http://localhost:9091/api/v1/config/reload
```
## Metrics
When metrics are enabled, the gateway exposes Prometheus-compatible metrics at `:9090/metrics`:
| Metric | Type | Description |
|-----------------------------------------|-----------|------------------------------------------|
| `gateway_http_requests_total` | Counter | Total HTTP requests by method/path/status |
| `gateway_http_request_duration_seconds` | Histogram | Request latency distribution |
| `gateway_http_active_requests` | Gauge | Currently in-flight requests |
| `gateway_upstream_errors_total` | Counter | Upstream error count by type |
| `gateway_circuit_breaker_state` | Gauge | Circuit state (0=closed, 1=open, 2=half) |
## Project Structure
```
go-api-gateway/
├── cmd/gateway/
│ └── main.go # Entry point, server lifecycle, graceful shutdown
├── internal/
│ ├── config/ # YAML config loader with Viper, hot-reload
│ ├── proxy/ # Reverse proxy with dynamic routing (LPM)
│ ├── ratelimit/ # Token bucket rate limiter (in-memory)
│ ├── auth/ # JWT validation, claims context, middleware
│ ├── circuit/ # Circuit breaker (closed → open → half-open)
│ ├── middleware/ # Request ID, CORS, logging, recovery, metrics
│ ├── admin/ # Admin REST API (gorilla/mux)
│ └── metrics/ # Prometheus metric recording
├── pkg/cache/ # Redis client wrapper
├── configs/
│ └── gateway.yaml # Sample configuration
├── deployments/
│ ├── Dockerfile # Multi-stage scratch build
│ ├── docker-compose.yml # Full stack (gateway + redis + postgres + prometheus + grafana)
│ └── prometheus.yml # Prometheus scrape config
├── .github/workflows/
│ └── ci.yml # Lint → Test → Build → Docker
├── Makefile # build, test, lint, docker, run targets
├── go.mod
└── README.md
```
## Development
```bash
# Run all tests
make test
# Run tests with coverage report
make test-cover
# Run benchmarks
make bench
# Format and vet
make lint
# Build and run locally
make run
# Build Docker image
make docker
```
## Benchmarks
> Benchmarked on Apple M2 Pro / Go 1.22 / Linux
| Component | Operation | ops/sec | ns/op | allocs/op |
|------------------|-----------------|---------------|--------|-----------|
| Token Bucket | Allow (single) | 30,000,000+ | ~33 | 0 |
| Token Bucket | Allow (parallel)| 10,000,000+ | ~100 | 0 |
| Circuit Breaker | Execute (closed)| 50,000,000+ | ~20 | 0 |
| Reverse Proxy | Route lookup | 20,000,000+ | ~50 | 0 |
**Target production performance:**
- **10,000+ RPS** with < 5ms p99 latency
- **Zero-downtime** configuration reload
- **90%+ test coverage** on core packages
## Tech Stack
| Technology | Purpose |
|-------------------|-----------------------------------|
| **Go 1.22+** | Core language (net/http, goroutines) |
| **Redis** | Rate limiting, caching |
| **PostgreSQL** | API key management, analytics |
| **Prometheus** | Metrics collection |
| **Grafana** | Monitoring dashboards |
| **Docker** | Containerization |
| **GitHub Actions** | CI/CD pipeline |
| **zerolog** | Structured JSON logging |
| **Viper** | Configuration management |
| **gorilla/mux** | Admin API routing |
## Contributing
Contributions are welcome! Please follow these steps:
1. Fork the repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Write tests for your changes
4. Ensure all tests pass (`make test`)
5. Run linting (`make lint`)
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request
### Code Style
- Follow standard Go conventions ([Effective Go](https://go.dev/doc/effective_go))
- Use `go fmt` and `go vet` before committing
- Write table-driven tests where appropriate
- Keep functions focused and under 50 lines when possible
## License
This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
---
**Built with ❤️ by [Kasidit Wansudon](https://github.com/kasidit-wansudon)**