1

I'm performing the following request in 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))

I want the host to be specified also in the path of the post request. Is it possible?

Expected result:

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

Actual result:

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

2 Answers 2

2

Set the Request.URL to an opaque URL. The opaque URL is written to the request line as is.

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,
    }

The http.NewRequest and http.NewRequestContext functions are the preferred way to create a request value. Set Request.URL to the opaque URL after creating the request with one of these functions:

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)
Sign up to request clarification or add additional context in comments.

Comments

0

what value of the URL variable? I think you can define the URL variable use a specific host

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

In case your path is dynamic from another variable, you can use fmt.Sprintf, like below

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

1 Comment

The question is not about the path / URL to post to, it's about the URL in the POST line of the HTTP protocol.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.