Go (net/http)
Go 语言专为极致网络性能而生。得益于 ProxyTracer 低于 10ms 的响应速度,在标准 net/http 中间件中调用它不会对 goroutine 造成任何可感知的性能瓶颈。
中间件实现
此实现安全地从 X-Forwarded-For 请求头提取 IP,利用配置了严格超时的 Go 原生 http.Client,在恶意连接触及核心业务逻辑前将其迅速阻断。
package middleware
import (
"encoding/json"
"log"
"net/http"
"os"
"strings"
"time"
)
// ProxyTracerResponse 精确映射到 {"proxy": true|false} JSON 响应
type ProxyTracerResponse struct {
Proxy bool `json:"proxy"`
}
func ProxyTracer(next http.Handler) http.Handler {
apiKey := os.Getenv("PROXYTRACER_API_KEY")
// 初始化带有严格 500ms 超时的可复用客户端
client := &http.Client{
Timeout: 500 * time.Millisecond,
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 1. 安全提取负载均衡器背后的真实 IP
ip := r.Header.Get("X-Forwarded-For")
if ip == "" {
ip = strings.Split(r.RemoteAddr, ":")[0]
} else {
ip = strings.Split(ip, ",")[0]
}
ip = strings.TrimSpace(ip)
// 若为本地开发环境则直接放行
if ip == "127.0.0.1" || ip == "::1" || ip == "" {
next.ServeHTTP(w, r)
return
}
// 2. 查询 ProxyTracer API
req, err := http.NewRequest("GET", "https://api.proxytracer.com/v1/check/"+ip, nil)
if err == nil {
req.Header.Set("Authorization", "Bearer "+apiKey)
resp, err := client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
defer resp.Body.Close()
var ptResp ProxyTracerResponse
if err := json.NewDecoder(resp.Body).Decode(&ptResp); err == nil {
// 3. 若检测到代理/VPN,则立即丢弃连接
if ptResp.Proxy {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"error": "Access Denied: VPN or Proxy detected."}`))
return // 提前终止处理器链执行
}
}
} else {
// 故障开放(Fail-open):记录错误并放行请求以确保可用性
log.Printf("ProxyTracer API error: %v", err)
}
}
// 4. 流量正常,继续进入下一个处理器
next.ServeHTTP(w, r)
})
}使用方法
只需使用该中间件包装您的主路由多路复用器或特定的敏感端点即可:
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api/secure-data", secureHandler)
// 使用 ProxyTracer 中间件包装整个路由器多路复用器
log.Fatal(http.ListenAndServe(":8080", middleware.ProxyTracer(mux)))
}最后更新于