eriel marimon eriel marimon - 5 months ago 8
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)
checkForError(err)
bodyString = string(bodyBytes)

fmt.Fprintf(w, bodyString)
}


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

http.Post("https://httpbin.org/post", "application/json; charset=utf-8", jsonData)

Answer

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("https://httpbin.org/post", "application/json; charset=utf-8", reader)

//or you can do it directly
//http.Post("https://httpbin.org/post", "application/json; charset=utf-8", resp.Body)