Skip to content

Commit a53501f

Browse files
authored
Merge pull request #9 from zerodha/feat-ptr-scan
Add support for scanning to *ptr fields.
2 parents e80eb9b + cc2d14c commit a53501f

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

fastglue_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,9 @@ func TestScanArgs(t *testing.T) {
696696
Str1 string `url:"str1"`
697697
StrBlock string `url:"-"`
698698
StrNoTag *string
699+
StrPtr1 *string `url:"strptr1"`
700+
StrPtr2 *string `url:"strptr2"`
701+
IntPtr *int `url:"intptr"`
699702
Strings []string `url:"str"`
700703
Bytes []byte `url:"bytes"`
701704
Int1 int `url:"int1"`
@@ -732,13 +735,21 @@ func TestScanArgs(t *testing.T) {
732735
args.Add("bool", "t")
733736
args.Add("custom", "bar")
734737
args.Add("custom_pointer", "bar")
738+
args.Add("strptr1", "strptrval")
739+
args.Add("intptr", "12345")
735740

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

746+
var (
747+
strPtr1 = "strptrval"
748+
intPtr = 12345
749+
)
741750
exp := test{
751+
StrPtr1: &strPtr1,
752+
IntPtr: &intPtr,
742753
Str1: "string1",
743754
Strings: []string{"str1", "str2", "str3"},
744755
Bytes: []byte("manybytes"),

utils.go

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,11 @@ import (
1818
// bool, number types and their slices.
1919
//
2020
// eg:
21-
// type Order struct {
22-
// Tradingsymbol string `url:"tradingsymbol"`
23-
// Tags []string `url:"tag"`
24-
// }
21+
//
22+
// type Order struct {
23+
// Tradingsymbol string `url:"tradingsymbol"`
24+
// Tags []string `url:"tag"`
25+
// }
2526
func ScanArgs(args *fasthttp.Args, obj interface{}, fieldTag string) ([]string, error) {
2627
ob := reflect.ValueOf(obj)
2728
if ob.Kind() == reflect.Ptr {
@@ -153,6 +154,21 @@ func setVal(f reflect.Value, val string) (bool, error) {
153154
f.Set(reflect.ValueOf(receiver))
154155
return true, nil
155156
}
157+
} else {
158+
// Create a new value of the type that the pointer points to
159+
typ := f.Type().Elem()
160+
newEl := reflect.New(typ)
161+
162+
ok, err := setVal(newEl.Elem(), val)
163+
if err != nil {
164+
return false, err
165+
}
166+
167+
// If the value was successfully set, point the original field to the new element
168+
if ok {
169+
f.Set(newEl)
170+
}
171+
return ok, nil
156172
}
157173

158174
return false, nil

0 commit comments

Comments
 (0)