Golang创建Toxiproxy代理连接非本地上游地址返回HTTP 404
Toxiproxy代理远程HTTP服务器返回404的解决方法
问题原因
Toxiproxy是TCP层透明代理,仅负责转发原始TCP流量,不会修改HTTP请求中的Host头部字段。当你向localhost:8000发起请求时,请求的Host头为localhost:8000,而example.com这类远程服务器(尤其是CDN托管站点)会严格根据Host头匹配站点资源,因此返回404错误。
你用curl测试时,响应中的Server: ECAcc也证明请求已到达example.com的CDN节点,但因Host头不匹配被拒绝。
解决方案
1. 手动指定正确的Host头(Go代码示例)
发起请求时显式设置Host为目标域名:
package main import ( "log" "net/http" toxiproxy "github.com/Shopify/toxiproxy/v2/client" ) func main() { client := toxiproxy.NewClient("localhost:8474") proxy, err := client.CreateProxy("my_http_proxy", "localhost:8000", "example.com:80") if err != nil { log.Fatal(err) } defer proxy.Delete() _, err = proxy.AddToxic("latency", "latency", "downstream", 1.0, toxiproxy.Attributes{ "latency": 1000, "jitter": 0, }) if err != nil { log.Fatal(err) } // 自定义请求并设置正确的Host头 req, err := http.NewRequest("GET", "http://localhost:8000/", nil) if err != nil { log.Fatal(err) } req.Host = "example.com" resp, err := http.DefaultClient.Do(req) if err != nil { log.Println(err) return } defer resp.Body.Close() log.Println(resp.StatusCode) // 此时会返回200 }
2. curl测试时指定Host头
curl -H "Host: example.com" localhost:8000
补充说明
本地服务器能正常工作,是因为多数本地开发服务器不会严格校验Host头,会默认返回站点内容;而远程生产服务器(尤其是CDN)对Host头的校验是核心路由逻辑,因此必须匹配正确域名。
内容的提问来源于stack exchange,提问作者face-palm
相关产品推荐
相关产品推荐

