March 9, 2017

How to reuse HTTP response body in Golang

Took me a while to figure it out, but it seems that in golang you cant re-read from an http response.

I found here a way to solve it.

For debugging purposes, I had to be able to print the raw response as well as decoding it to json, to make sure that the json decoder was decoding properly

Basically you can reset the http response body “read state” by doing this:

	//perform http request
	resp, err := http.Post(url, "application/json; charset=utf-8", bytes.NewBuffer(requestData))
	defer resp.Body.Close()
	utils.CheckErr(err)

	// read the response body to a variable
	bodyBytes, _ := ioutil.ReadAll(resp.Body)
    bodyString := string(bodyBytes)
	//print raw response body for debugging purposes
    fmt.Println("\n\n", bodyString, "\n\n")
  	
    //reset the response body to the original unread state
	resp.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))


	// Step 3
	oR := new(jsonResponse)
	json.NewDecoder(resp.Body).Decode(oR)

Powered by Hugo & Kiss.