Golang http 请求在 POST 路径中指定主机

Golang http request specify host in POST path

我正在 golang 中执行以下请求:

request := &http.Request{
        URL:           url,
        Body:          requestBody, //io.ReadCloser containing the body
        Method:        http.MethodPost,
        ContentLength: int64(len(postBody)),
        Header:        make(http.Header),
        Proto:         "HTTP/1.1",
        ProtoMajor:    1,
        ProtoMinor:    1,
    }

res, err := http.DefaultClient.Do(request)

//Printing the request:
dump, dumpErr := httputil.DumpRequest(request, true)
if dumpErr != nil {
   log.Fatal("Cannot dump the request")
}
log.Println(string(dump))

我希望在post请求路径中也指定主机。可能吗?

预期结果:

POST "http://127.0.0.1:10019/system?action=add_servers" HTTP/1.1
Host: 127.0.0.1:10019
Accept: "*/*"
Connection: keep-alive

实际结果:

POST "/system?action=add_servers" HTTP/1.1
Host: 127.0.0.1:10019
Accept: "*/*"
Connection: keep-alive

URL 变量的值是多少? 我想你可以定义 URL 变量使用特定的主机

var url = "http://127.0.0.1:10019/system?action=add_servers"

如果您的路径是来自另一个变量的动态路径,您可以使用 fmt.Sprintf,如下所示

// assume url value
var path = "/system?action=add_servers" 
url = fmt.Sprintf("http://127.0.0.1:10019/%s", path)

设置Request.URL to an opaque URL。不透明的 URL 按原样写入请求行。

request := &http.Request{
        URL:           &url.URL{Opaque: "http://127.0.0.1:10019/system?action=add_servers"}
        Body:          requestBody, //io.ReadCloser containing the body
        Method:        http.MethodPost,
        ContentLength: int64(len(postBody)),
        Header:        make(http.Header),
        Proto:         "HTTP/1.1",
        ProtoMajor:    1,
        ProtoMinor:    1,
    }

http.NewRequest and http.NewRequestContext 函数是创建请求值的首选方法。使用以下函数之一创建请求后,将 Request.URL 设置为不透明的 URL:

u := "http://127.0.0.1:10019/system?action=add_servers"
request, err := http.NewRequest("POST", u, requestBody)
if err != nil {
    // handle error
}
request.URL = &url.URL{Opaque: u}

res, err := http.DefaultClient.Do(request)