Skip to content

Commit

Permalink
support nil pointer and pointer of pointer in SetResult and SetError(i…
Browse files Browse the repository at this point in the history
  • Loading branch information
imroc committed Aug 7, 2022
1 parent 059a0ee commit 36341da
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
26 changes: 22 additions & 4 deletions internal/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,29 @@ func IsXMLType(ct string) bool {

// GetPointer return the pointer of the interface.
func GetPointer(v interface{}) interface{} {
vv := reflect.ValueOf(v)
if vv.Kind() == reflect.Ptr {
return v
t := reflect.TypeOf(v)
if t.Kind() == reflect.Ptr {
if tt := t.Elem(); tt.Kind() == reflect.Ptr { // pointer of pointer
if tt.Elem().Kind() == reflect.Ptr {
panic("pointer of pointer of pointer is not supported")
}
el := reflect.ValueOf(v).Elem()
if el.IsZero() {
vv := reflect.New(tt.Elem())
el.Set(vv)
return vv.Interface()
} else {
return el.Interface()
}
} else {
if reflect.ValueOf(v).IsZero() {
vv := reflect.New(t.Elem())
return vv.Interface()
}
return v
}
}
return reflect.New(vv.Type()).Interface()
return reflect.New(t).Interface()
}

// GetType return the underlying type.
Expand Down
20 changes: 20 additions & 0 deletions request_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,26 @@ func TestSetBodyMarshal(t *testing.T) {
}
}

func TestSetResult(t *testing.T) {
c := tc()
var user *UserInfo
url := "/search?username=imroc&type=json"

resp, err := c.R().SetResult(&user).Get(url)
assertSuccess(t, resp, err)
tests.AssertEqual(t, "imroc", user.Username)

user = &UserInfo{}
resp, err = c.R().SetResult(user).Get(url)
assertSuccess(t, resp, err)
tests.AssertEqual(t, "imroc", user.Username)

user = nil
resp, err = c.R().SetResult(user).Get(url)
assertSuccess(t, resp, err)
tests.AssertEqual(t, "imroc", resp.Result().(*UserInfo).Username)
}

func TestSetBody(t *testing.T) {
body := "hello"
fn := func() (io.ReadCloser, error) {
Expand Down

0 comments on commit 36341da

Please sign in to comment.