eriel marimon eriel marimon - 1 year ago 89
JSON Question

Go: How do I turn response body into request body?

I have a handler that makes a request to elasticsearch.
I cat get the json response from that request:

resp, err := http.Get(getUrl)
defer resp.Body.Close()
bodyString := ""
if resp.StatusCode == 200{
bodyBytes, err := ioutil.ReadAll(resp.Body)
bodyString = string(bodyBytes)

fmt.Fprintf(w, bodyString)

How do I turn that
into something I can pass to an http.Post of this sort:

http.Post("", "application/json; charset=utf-8", jsonData)

Answer Source

I am not really sure what are you trying to achive, but may be it help.

bodyBytes, err := ioutil.ReadAll(resp.Body)
reader := bytes.NewReader(bodyBytes)
http.Post("", "application/json; charset=utf-8", reader)

//or you can do it directly
//http.Post("", "application/json; charset=utf-8", resp.Body)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download