initial
This commit is contained in:
28
structscanner.go
Normal file
28
structscanner.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package webutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
// ScanStruct scans form values into the exported fields of dest (must be a
|
||||
// pointer to a struct) using field names as form keys. Bool fields are set to
|
||||
// true when the key is present, matching HTML checkbox behaviour.
|
||||
func ScanStruct(form url.Values, dest any) error {
|
||||
v := reflect.ValueOf(dest)
|
||||
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Struct {
|
||||
return errors.New("ScanStruct: dest must be a pointer to a struct")
|
||||
}
|
||||
v = v.Elem()
|
||||
|
||||
s := NewFormScanner(form)
|
||||
for key := range form {
|
||||
fv := v.FieldByName(key)
|
||||
if !fv.IsValid() || !fv.CanSet() {
|
||||
continue
|
||||
}
|
||||
s.Scan(key, fv.Addr().Interface())
|
||||
}
|
||||
return s.Error()
|
||||
}
|
||||
Reference in New Issue
Block a user