diff --git a/netutil/request.go b/netutil/request.go index b438687..ed63372 100644 --- a/netutil/request.go +++ b/netutil/request.go @@ -12,6 +12,8 @@ package netutil import ( + "encoding/json" + "errors" "fmt" "net/http" "sort" @@ -43,6 +45,15 @@ func HttpPatch(url string, params ...interface{}) (*http.Response, error) { return request(http.MethodPatch, url, params...) } +// ParseResponse convert the http response to interface{} obj +func ParseResponse(resp *http.Response, obj interface{}) error { + if resp == nil { + return errors.New("InvalidResp") + } + defer resp.Body.Close() + return json.NewDecoder(resp.Body).Decode(obj) +} + // ConvertMapToQueryString convert map to sorted url query string func ConvertMapToQueryString(param map[string]interface{}) string { if param == nil { diff --git a/netutil/request_test.go b/netutil/request_test.go index 639ef32..ec8fd61 100644 --- a/netutil/request_test.go +++ b/netutil/request_test.go @@ -102,3 +102,27 @@ func TestConvertMapToQueryString(t *testing.T) { t.FailNow() } } + +func TestParseResponse(t *testing.T) { + url := "http://public-api-v1.aspirantzhang.com/users" + type User struct { + Id int `json:"id"` + Name string `json:"name"` + Email string `json:"email"` + } + type UserResp struct { + Data []User `json:"data"` + } + resp, err := HttpGet(url) + if err != nil { + log.Fatal(err) + t.FailNow() + } + userResp := &UserResp{} + err = ParseResponse(resp, userResp) + if err != nil { + log.Fatal(err) + t.FailNow() + } + fmt.Println(userResp.Data) +}