Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for scanning to *ptr fields. #9

Merged
merged 1 commit into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading