Go - After request headers are set, request body is empty

Viewed 30

To create an outgoing POST request, func NewRequest() from net/http library is used. request body is parsed as a param. After request is created I set request headers using Set() func. After setting headers, request body is empty.

// create a new request 
req, err = http.NewRequest(method, url string, body io.Reader) (*Request, error)
// set headers 
// when I print req.Body at this stage, it's not empty
req.Header.set("foo", "bar")
// when I print req.Body at this stage, it's empty

Any of you have met this problem before? and any idea for this?

1 Answers

You would need Request.GetBody() to read/print the Body content without emptying it, as a client requests.

    // GetBody defines an optional func to return a new copy of
    // Body. It is used for client requests when a redirect requires
    // reading the body more than once. Use of GetBody still
    // requires setting Body.
    //
    // For server requests, it is unused.
    GetBody func() (io.ReadCloser, error)

Since:

  • NewRequest wraps NewRequestWithContext using context.Background
  • NewRequestWithContext set getBody()

You should have that function already defined for your http.NewRequest request.

Related