Skip to content

Instantly share code, notes, and snippets.

@glucn
Created October 19, 2019 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glucn/e026505175727a7da8b5558683364690 to your computer and use it in GitHub Desktop.
Save glucn/e026505175727a7da8b5558683364690 to your computer and use it in GitHub Desktop.
Decode HTTP Response - version 3
import (
"encoding/json"
"errors"
"net/http"
)
type Customer struct {
ID string `json:"id"`
Name string `json:"name"`
}
func dataFromResponse(r *http.Response) (*Customer, error) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, util.Error(util.Internal, "failed to read the body of response: %s", err.Error())
}
defer r.Body.Close()
type Response struct {
Customer *Customer `json:"data"`
}
res := Response{}
if err := json.Unmarshal(body, &res); err != nil {
return nil, errors.New("failed to convert response to Customer: %s", err.Error())
}
return res.Customer, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment