gogoquery

How to parse copy of variable instead of pointer in go?


In below code snippet I parse http response body 'b' to func parseGoQuery and it is ok first time, but when I do it second time in main() it shows me that response 'b' is 0 inside func parseGoQuery. I think I pass copy of variable 'b' , not pointer, I am confused...please advice

resp, _ := client.Get(URL)
    b :=resp.Body

    defer b.Close() // close Body when the function returns
        parseGoQuery("tag1", b)  //b is not 0 as expected, good
    parseGoQuery("tag2", b)  //b is 0 !!!???

Here is func parseGoQuery

func parseGoQuery(tag string, b io.Reader) {
    fmt.Println(tag,b)
//skipped
}

Solution

  • Response.body is of type io.Readcloser. So once you read from the body, it will get closed and further attempts to read from it will give a zero value. You can only read from the body once.

    So, Store the data you have read from body in a variable and pass that variable to that function.