88 lines
1.9 KiB
Go
88 lines
1.9 KiB
Go
package validation
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
|
|
"git.haelnorr.com/h/golib/hws"
|
|
"git.haelnorr.com/h/timefmt"
|
|
)
|
|
|
|
// QueryGetter wraps http.Request to get query values
|
|
type QueryGetter struct {
|
|
r *http.Request
|
|
checks []*ValidationRule
|
|
}
|
|
|
|
func NewQueryGetter(r *http.Request) *QueryGetter {
|
|
return &QueryGetter{r: r, checks: []*ValidationRule{}}
|
|
}
|
|
|
|
func (q *QueryGetter) Get(key string) string {
|
|
return q.r.URL.Query().Get(key)
|
|
}
|
|
|
|
func (q *QueryGetter) GetList(key string) []string {
|
|
return strings.Split(q.Get(key), ",")
|
|
}
|
|
|
|
func (q *QueryGetter) getChecks() []*ValidationRule {
|
|
return q.checks
|
|
}
|
|
|
|
func (q *QueryGetter) AddCheck(check *ValidationRule) {
|
|
q.checks = append(q.checks, check)
|
|
}
|
|
|
|
func (q *QueryGetter) ValidateChecks() []*ValidationRule {
|
|
return validate(q)
|
|
}
|
|
|
|
func (q *QueryGetter) String(key string) *StringField {
|
|
return newStringField(key, q)
|
|
}
|
|
|
|
func (q *QueryGetter) Int(key string) *IntField {
|
|
return newIntField(key, q)
|
|
}
|
|
|
|
func (q *QueryGetter) Bool(key string) *BoolField {
|
|
return newBoolField(key, q)
|
|
}
|
|
|
|
func (q *QueryGetter) Time(key string, format *timefmt.Format) *TimeField {
|
|
return newTimeField(key, format, q)
|
|
}
|
|
|
|
func (q *QueryGetter) StringList(key string) *StringList {
|
|
return newStringList(key, q)
|
|
}
|
|
|
|
func (q *QueryGetter) IntList(key string) *IntList {
|
|
return newIntList(key, q)
|
|
}
|
|
|
|
func (q *QueryGetter) Validate() bool {
|
|
return len(validate(q)) == 0
|
|
}
|
|
|
|
// ValidateAndNotify runs the provided validation checks and sends a notification for each failed check
|
|
// Returns true if all checks passed
|
|
func (q *QueryGetter) ValidateAndNotify(
|
|
s *hws.Server,
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) bool {
|
|
return validateAndNotify(s, w, r, q)
|
|
}
|
|
|
|
// ValidateAndError runs the provided validation checks and renders an error page with all the error messages
|
|
// Returns true if all checks passed
|
|
func (q *QueryGetter) ValidateAndError(
|
|
s *hws.Server,
|
|
w http.ResponseWriter,
|
|
r *http.Request,
|
|
) bool {
|
|
return validateAndError(s, w, r, q)
|
|
}
|