Golang HTTP client. Do (req) cannot be used two times

Source: Internet
Author: User

Initializing the client, and the request unexpectedly cannot be called the second time, odd eight strange.

Not much to read the source, but know where the problem.

First the code looks like this:

resp, err := client.Do(req)resp, err := client.Do(req)

Originally thought about a period of time to refresh the data, to see what changes in the data, so I think can be reused req, but did not expect the error:

: http: ContentLength=15 with Body length 0

What is this for? In-depth investigation, first look at the req long what kind of

req, err = http.NewRequest("POST", "some url", strings.NewReader("articleId="+articleId))

The third parameter is the body,
Req. Body length is like this:

type Reader struct {    s        string    i        int64 // current reading index    prevRune int   // index of previous rune; or < 0}

See this suddenly understand, client. The Do method reads the body data according to the I value in reader, that is, call its Read method, I value will change, of course, after reading, I value will become contentlength. Then the next time the use of the time, because no data can be read, resulting in the error Body length 0 .

How should the situation be solved?

。。。

New reader ...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.