尝试发送的请求的 header 的 Host 字段
request, err := http.NewRequest("GET", url, nil) request.Header.Set("Host","example.com")
这样写一直都是错误的 ,在 Request.header 有一句
For incoming requests, the Host header is promoted to the Request.Host field and removed from the Header map.
翻译就是
对于传入的请求,Host 标头被提升为
Request.Host 字段并从 Header 映射中移除。
必须要这样写
request.Host = "example.com"
附一个简单的调用:
package testapisix import ( "io/ioutil" "log" "net/http" "testing" ) func Test_GET(t *testing.T){ url := "http://127.0.0.1:9080/" request, e := http.NewRequest("GET", url, nil) if e != nil { t.Fatal(e) } request.Host = "example.com" client := &http.Client{} response, e := client.Do(request) if e != nil { t.Fatal(e) } defer response.Body.Close() log.Println(response.Header) body, _ := ioutil.ReadAll(response.Body) //读取body log.Println(string(body)) } func Test_POST(t *testing.T){ url := "http://127.0.0.1:9080/" request, e := http.NewRequest("POST", url, nil) if e != nil { t.Fatal(e) } request.Host = "example.com" csrfToken := "xxx" request.Header.Add("token",csrfToken) cc := new(http.Cookie) cc.Name = "token" cc.Value = csrfToken request.AddCookie(cc) client := &http.Client{} response, e := client.Do(request) if e != nil { t.Fatal(e) } defer response.Body.Close() log.Println(response.Header) body, _ := ioutil.ReadAll(response.Body) //读取body log.Println(string(body)) }
apisix 开启 csrf token
http://127.0.0.1:9080/apisix/admin/routes/1 POST header.X-API-KEY { "methods": ["GET","POST"], "host": "example.com", "uri": "/*", "plugins": { "csrf": { "name":"token", "key": "unique_key" } }, "upstream": { "type": "roundrobin", "nodes": { "web1:80": 1 } } }