- 路由转发
- 鉴权认证
- 限流熔断
- 日志监控
- 协议转换
package main
import (
"net/http"
"net/http/httputil"
"net/url"
)
type Gateway struct {
routes map[string]*httputil.ReverseProxy
limiter *RateLimiter
auth *AuthMiddleware
}
func (gw *Gateway) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// 1. 鉴权
if !gw.auth.Validate(r) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// 2. 限流
if !gw.limiter.Allow(r.RemoteAddr) {
http.Error(w, "Too Many Requests", http.StatusTooManyRequests)
return
}
// 3. 路由转发
path := r.URL.Path
proxy, ok := gw.routes[path]
if !ok {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
proxy.ServeHTTP(w, r)
}
func NewGateway() *Gateway {
gw := &Gateway{
routes: make(map[string]*httputil.ReverseProxy),
limiter: NewRateLimiter(100),
auth: NewAuthMiddleware(),
}
// 注册路由
gw.RegisterRoute("/api/users", "http://user-service:8080")
gw.RegisterRoute("/api/orders", "http://order-service:8080")
return gw
}
func (gw *Gateway) RegisterRoute(path, target string) {
targetURL, _ := url.Parse(target)
gw.routes[path] = httputil.NewSingleHostReverseProxy(targetURL)
}# Kong配置
services:
- name: user-service
url: http://user-service:8080
routes:
- name: user-route
paths:
- /api/users
plugins:
- name: rate-limiting
config:
minute: 100
- name: jwt关键要点:
- ✅ API网关是微服务入口
- ✅ 统一鉴权、限流、监控
- ✅ Kong成熟度高
- ✅ 自研灵活性强