Skip to content

Commit

Permalink
Add support for scanning to *ptr fields.
Browse files Browse the repository at this point in the history
  • Loading branch information
knadh committed Jan 24, 2024
1 parent e977d12 commit cc2d14c
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
11 changes: 11 additions & 0 deletions fastglue_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -696,6 +696,9 @@ func TestScanArgs(t *testing.T) {
Str1 string `url:"str1"`
StrBlock string `url:"-"`
StrNoTag *string
StrPtr1 *string `url:"strptr1"`
StrPtr2 *string `url:"strptr2"`
IntPtr *int `url:"intptr"`
Strings []string `url:"str"`
Bytes []byte `url:"bytes"`
Int1 int `url:"int1"`
Expand Down Expand Up @@ -732,13 +735,21 @@ func TestScanArgs(t *testing.T) {
args.Add("bool", "t")
args.Add("custom", "bar")
args.Add("custom_pointer", "bar")
args.Add("strptr1", "strptrval")
args.Add("intptr", "12345")

_, err := ScanArgs(args, &o, "url")
if err != nil {
t.Fatalf("Got unexpected error: %v", err)
}

var (
strPtr1 = "strptrval"
intPtr = 12345
)
exp := test{
StrPtr1: &strPtr1,
IntPtr: &intPtr,
Str1: "string1",
Strings: []string{"str1", "str2", "str3"},
Bytes: []byte("manybytes"),
Expand Down
24 changes: 20 additions & 4 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import (
// bool, number types and their slices.
//
// eg:
// type Order struct {
// Tradingsymbol string `url:"tradingsymbol"`
// Tags []string `url:"tag"`
// }
//
// type Order struct {
// Tradingsymbol string `url:"tradingsymbol"`
// Tags []string `url:"tag"`
// }
func ScanArgs(args *fasthttp.Args, obj interface{}, fieldTag string) ([]string, error) {
ob := reflect.ValueOf(obj)
if ob.Kind() == reflect.Ptr {
Expand Down Expand Up @@ -153,6 +154,21 @@ func setVal(f reflect.Value, val string) (bool, error) {
f.Set(reflect.ValueOf(receiver))
return true, nil
}
} else {
// Create a new value of the type that the pointer points to
typ := f.Type().Elem()
newEl := reflect.New(typ)

ok, err := setVal(newEl.Elem(), val)
if err != nil {
return false, err
}

// If the value was successfully set, point the original field to the new element
if ok {
f.Set(newEl)
}
return ok, nil
}

return false, nil
Expand Down

0 comments on commit cc2d14c

Please sign in to comment.