Skip to Content

Go (net/http)

Go está diseñado para servicios de red ultra rápidos. Debido a que ProxyTracer responde en menos de 10 ms, llamarlo dentro de un controlador de middleware estándar net/http no generará ningún cuello de botella perceptible en tus goroutines.

El Middleware

Esta implementación extrae con seguridad la IP de los encabezados X-Forwarded-For, utiliza el http.Client nativo de Go con un tiempo de espera estricto y desconecta las conexiones maliciosas inmediatamente antes de que alcancen la lógica principal de tu aplicación.

package middleware import ( "encoding/json" "log" "net/http" "os" "strings" "time" ) // ProxyTracerResponse maps exactly to the {"proxy": true|false} JSON response type ProxyTracerResponse struct { Proxy bool `json:"proxy"` } func ProxyTracer(next http.Handler) http.Handler { apiKey := os.Getenv("PROXYTRACER_API_KEY") // Initialize a reusable client with a strict 500ms timeout client := &http.Client{ Timeout: 500 * time.Millisecond, } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // 1. Safely extract the real IP behind load balancers 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) // Pass through if local development if ip == "127.0.0.1" || ip == "::1" || ip == "" { next.ServeHTTP(w, r) return } // 2. Query 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. Drop the connection if a proxy/VPN is detected 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 // Short-circuits the handler chain } } } else { // Fail open: Log the error and allow the request through to ensure uptime log.Printf("ProxyTracer API error: %v", err) } } // 4. Traffic is clean, proceed to the next handler next.ServeHTTP(w, r) }) }

Uso

Simplemente envuelve tu enrutador principal o puntos finales sensibles con el middleware:

func main() { mux := http.NewServeMux() mux.HandleFunc("/api/secure-data", secureHandler) // Wrap the entire multiplexer in the ProxyTracer middleware log.Fatal(http.ListenAndServe(":8080", middleware.ProxyTracer(mux))) }
Last updated on