29 lines
709 B
Go
29 lines
709 B
Go
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()
|
|
}
|