Created
October 19, 2019 23:15
-
-
Save glucn/3cf993bc52d6f20fc0757ddc5a3f30d9 to your computer and use it in GitHub Desktop.
Decode HTTP Response - version 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"encoding/json" | |
"errors" | |
"net/http" | |
) | |
type CustomerStringId struct { | |
ID string `json:"id"` | |
Name string `json:"name"` | |
} | |
type CustomerIntId struct { | |
ID string `json:"id,int"` // decode it from int in JSON to string | |
Name string `json:"name"` | |
} | |
func dataFromResponse(r *http.Response) (*Customer, error) { | |
// copy the content of response body, so it can be reused later | |
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 *CustomerStringId `json:"data"` | |
} | |
// try to decode body to CustomerStringId | |
res := Response{} | |
err = json.Unmarshal(body, &res) | |
if err != nil { | |
// if failed, try to decode body to CustomerIntId | |
type Response struct { | |
Customer *CustomerIntId `json:"data"` | |
} | |
resInt := Response{} | |
if err := json.Unmarshal(body, &resInt); err != nil { | |
return nil, errors.New("failed to convert response to Customer: %s", err.Error()) | |
} | |
// copy CustomerIntId to CustomerStringId | |
res.Customer.ID = resInt.Customer.ID | |
res.Customer.Name = resInt.Customer.Name | |
} | |
return res.Customer, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment