Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Response not getting cached when using .Bytes() or .String() methods #73

Open
HittingSmoke opened this issue Dec 5, 2018 · 1 comment

Comments

@HittingSmoke
Copy link

I read the response quirks on the readme but have so far been unable to get a struct populated using the response.JSON() method.

I'm using the latest version of grequests with Go 1.11. Here is the chunk of code in question:

        resp, _ := session.Post(loginapi, ro)

	fmt.Println(resp.Bytes())
	fmt.Println(resp.String()) // S1
	fmt.Println(resp.StatusCode)

	var r = new(APIResponse)

	fmt.Println(resp.JSON(&r))
	fmt.Println(resp.String()) // S2

In this scenario, S1 will print the response string and S2 will be empty. If I remove the resp.JSON() line everything works fine. Even if I try to call resp.JSON() first to populate before any other response method calls, the struct comes back nil.

@MarkusFreitag
Copy link

MarkusFreitag commented Feb 22, 2019

Please note that resp.JSON does return an error instead of your filled data struct. That is the reason, why you need to provide a pointer to it. So if resp.JSON returns nil no error occurred while unmarshaling the json string.

Code:

package main

import (
  "fmt"

  "github.com/levigross/grequests"
)

type jsonResponse struct {
  Message string `json:"message"`
}

func main() {
  resp, _ := grequests.Get("http://127.0.0.1:8080/", nil)
  fmt.Println("before resp.JSON")
  fmt.Printf("resp.Bytes() => %v\n", resp.Bytes())
  fmt.Printf("resp.String() => %v\n", resp.String())
  fmt.Printf("resp.StatusCode => %d\n\n", resp.StatusCode)

  var r = new(jsonResponse)
  resp.JSON(&r)
  fmt.Println("after resp.JSON")
  fmt.Printf("json struct => %v\n", r)
  fmt.Printf("resp.Bytes() => %v\n", resp.Bytes())
  fmt.Printf("resp.String() => %v\n", resp.String())
  fmt.Printf("resp.StatusCode => %d\n", resp.StatusCode)
}

Output:

before resp.JSON
resp.Bytes() => [123 34 109 101 115 115 97 103 101 34 58 34 109 111 111 34 125]
resp.String() => {"message":"moo"}
resp.StatusCode => 200

after resp.JSON
json struct => &main.jsonResponse{Message:"moo"}
resp.Bytes() => []
resp.String() => 
resp.StatusCode => 200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants