go/webutil/formscanner.go
2024-11-15 19:27:39 +01:00

40 lines
616 B
Go

package webutil
import (
"errors"
"fmt"
"net/url"
)
var ErrUnsupportedType = errors.New("unsupported type")
type FormScanner struct {
form url.Values
err error
}
func NewFormScanner(form url.Values) *FormScanner {
return &FormScanner{form: form}
}
func (s *FormScanner) Scan(name string, val any) *FormScanner {
if s.err != nil {
return s
}
switch v := val.(type) {
case *bool:
*v = s.form.Has(name)
default:
if err := scan(s.form.Get(name), v); err != nil {
s.err = fmt.Errorf("Error in field %s: %w", name, err)
}
}
return s
}
func (s *FormScanner) Error() error {
return s.err
}