Create a program that implements shadow traffic routing.
- User
Create a program that implements shadow traffic routing.
Assistant
Create a program that implements shadow traffic routing.
The user wants a program that implements "shadow traffic routing".
1. Understand the Concept:
2. Choose the Tech Stack:
net/http is sufficient and often preferred for clarity in demonstrating core concepts, rather than hiding logic behind a framework like Gin or Echo.3. Design the Implementation:
Scenario: A simple HTTP Reverse Proxy.
Steps:
io.Reader instances (one for primary, one for shadow).4. Refinement & Edge Cases:
req.Body is consumed.io.ReadAll then bytes.NewReader (or bytes.NewBuffer). Set req.GetBody if we were writing a standard library transport, but here we are constructing new requests manually, so just creating new readers is fine.5. Drafting the Code (Mental or Scratchpad):
Main:
backendPrimary on 8081.backendShadow on 8082.proxy on 8080.Proxy Handler:
body, _ := io.ReadAll(r.Body)reqPrimary, _ := http.NewRequest(..., bytes.NewReader(body))reqShadow, _ := http.NewRequest(..., bytes.NewReader(body))go func() { client.Do(reqShadow) }()resp, _ := client.Do(reqPrimary)resp to w.6. Adding Explanations:
7. Python Alternative?
aiohttp or just threading?8. Final Code Structure (Go):
main function setup.mockBackend handler (prints what it got).shadowProxyHandler (the logic).
9. Self-Correction during drafting:
10. Output Generation: (Proceeding to generate the Go code and explanation).
I have chosen Go because its concurrency model (Goroutines) is ideal for handling the "fire-and-forget" nature of shadow traffic without delaying the main user response.
Save this into a file named main.go.
package main
import (
"bytes"
"context"
"fmt"
"io"
"log"
"net/http"
"time"
)
// Configuration
const (
// The port our router listens on
ListenAddr = ":8080"
// The actual production service
LiveServiceURL = "http://localhost:8081/live"
// The experimental/shadow service
ShadowServiceURL = "http://localhost:8082/shadow"
)
func main() {
// 1. Start Mock Backends (So we can test this program)
go startMockBackend("Live Service", ":8081", false)
go startMockBackend("Shadow Service", ":8082", true)
// 2. Configure the Router
http.HandleFunc("/", shadowTrafficHandler)
fmt.Printf("🚀 Shadow Router listening on %s\n", ListenAddr)
fmt.Println("Press Ctrl+C to stop.")
// 3. Start the Server
if err := http.ListenAndServe(ListenAddr, nil); err != nil {
log.Fatalf("Server failed: %v", err)
}
}
// shadowTrafficHandler handles the incoming client request
func shadowTrafficHandler(w http.ResponseWriter, r *http.Request) {
// Step 1: Read the request body into a byte slice.
// We must do this because r.Body is a stream that can only be read once.
// We need two copies: one for Live, one for Shadow.
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read request body", http.StatusInternalServerError)
return
}
// Important: Close the original body when done
defer r.Body.Close()
// Step 2: Send to Shadow Service (Asynchronously)
// We use 'go' to launch this in a separate thread (goroutine).
// The main thread does not wait for this to finish.
go sendToShadow(r, bodyBytes)
// Step 3: Send to Live Service (Synchronously)
// We wait for this response because we need to return it to the client.
liveResp, err := sendToLive(r, bodyBytes)
if err != nil {
http.Error(w, "Live service unavailable", http.StatusBadGateway)
log.Printf("Error calling live service: %v", err)
return
}
defer liveResp.Body.Close()
// Step 4: Copy Live Response headers and body to Client
copyHeaders(w.Header(), liveResp.Header)
w.WriteHeader(liveResp.StatusCode)
io.Copy(w, liveResp.Body)
}
// sendToLive forwards the request to the production endpoint
func sendToLive(originalReq *http.Request, body []byte) (*http.Response, error) {
client := http.Client{Timeout: 5 * time.Second}
// Create a new request for the live service
req, err := http.NewRequest(originalReq.Method, LiveServiceURL, bytes.NewReader(body))
if err != nil {
return nil, err
}
// Copy original headers
copyHeaders(req.Header, originalReq.Header)
log.Println("➡️ Forwarding request to LIVE service...")
return client.Do(req)
}
// sendToShadow forwards the request to the shadow endpoint
func sendToShadow(originalReq *http.Request, body []byte) {
// Create a context with a timeout for the shadow request.
// If the shadow service is slow, we don't want hanging goroutines forever.
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
client := http.Client{Timeout: 3 * time.Second}
// Create a new request using the original method and the body copy
req, err := http.NewRequestWithContext(ctx, originalReq.Method, ShadowServiceURL, bytes.NewReader(body))
if err != nil {
log.Printf("Shadow request creation failed: %v", err)
return
}
// Copy headers (Shadows usually need to know content-type, auth tokens, etc.)
copyHeaders(req.Header, originalReq.Header)
// Add a custom header so the shadow service knows this is mirrored traffic
req.Header.Set("X-Shadow-Traffic", "true")
log.Println("👥 Mirroring request to SHADOW service...")
resp, err := client.Do(req)
if err != nil {
log.Printf("⚠️ Shadow request failed (ignored): %v", err)
return
}
// We must read and close the response body to reuse the connection
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
// Helper: Copy headers from source to destination
func copyHeaders(dst, src http.Header) {
for k, vv := range src {
for _, v := range vv {
dst.Add(k, v)
}
}
}
// --- Mock Backend Helpers for Demonstration ---
func startMockBackend(name string, addr string, simulateSlow bool) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Simulate slowness for shadow traffic to prove the client doesn't wait
if simulateSlow {
time.Sleep(2 * time.Second)
}
// Read body to prove we received it
body, _ := io.ReadAll(r.Body)
fmt.Printf("[%s] Received request: %s %s (Body: %s)\n", name, r.Method, r.URL.Path, string(body))
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Response from %s", name)
})
http.ListenAndServe(addr, handler)
}
Save the code to main.go.
Open a terminal and run it:
go run main.go
Open a separate terminal to simulate a Client request using curl:
curl -X POST -d "Hello World" http://localhost:8080
curl command will return instantly with Response from Live Service.Body Buffering (io.ReadAll):
HTTP request bodies are streams that can only be read once. To send the traffic to two places, we must read the entire body into memory ([]byte) first, then create two new readers (bytes.NewReader) to send to the backends.
Note: In high-throughput production systems, buffering large files in memory can cause RAM issues.
Goroutines (go sendToShadow):
This is the magic keyword. By adding go before the function call, the program spins off that task to run in the background. The code immediately continues to the "Live" section without waiting for the Shadow function to return.
Discarding Response (io.Discard):
In the sendToShadow function, we read the response body into io.Discard. This is important for Go's HTTP performance; if you don't read the response body, the connection cannot be reused (keep-alive) and will leak resources.
Timeouts: Shadow traffic should always have strict timeouts. If your shadow service hangs, you don't want thousands of Goroutines piling up in your router waiting forever.