fix: reqdata checks for missing form input globally for json, multipart, url encoded

This commit is contained in:
Adrien Marquès 2021-06-22 23:43:15 +02:00
parent 90e62b7e72
commit 3613581b1c
Signed by: xdrm-brackets
GPG Key ID: D75243CA236D825E
1 changed files with 26 additions and 26 deletions

View File

@ -106,24 +106,32 @@ func (i *T) GetForm(req http.Request) error {
ct := req.Header.Get("Content-Type")
switch {
case strings.HasPrefix(ct, "application/json"):
return i.parseJSON(req)
err := i.parseJSON(req)
if err != nil {
return err
}
case strings.HasPrefix(ct, "application/x-www-form-urlencoded"):
return i.parseUrlencoded(req)
err := i.parseUrlencoded(req)
if err != nil {
return err
}
case strings.HasPrefix(ct, "multipart/form-data; boundary="):
return i.parseMultipart(req)
default:
err := i.parseMultipart(req)
if err != nil {
return err
}
}
// fail on at least 1 mandatory form param when there is no body
for name, param := range i.service.Form {
if !param.Optional {
_, exists := i.Data[param.Rename]
if !exists && !param.Optional {
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
}
}
return nil
}
}
// parseJSON parses JSON from the request body inside 'Form'
@ -133,19 +141,17 @@ func (i *T) parseJSON(req http.Request) error {
decoder := json.NewDecoder(req.Body)
err := decoder.Decode(&parsed)
if err != io.EOF {
if err == io.EOF {
return nil
}
if err != nil {
return fmt.Errorf("%s: %w", err, ErrInvalidJSON)
}
}
for name, param := range i.service.Form {
value, exist := parsed[name]
if !exist {
if !param.Optional {
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
}
continue
}
@ -170,9 +176,6 @@ func (i *T) parseUrlencoded(req http.Request) error {
values, exist := req.PostForm[name]
if !exist {
if !param.Optional {
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
}
continue
}
@ -204,7 +207,7 @@ func (i *T) parseMultipart(req http.Request) error {
return nil
}
if err != nil {
return err
return fmt.Errorf("%s: %w", err, ErrInvalidMultipart)
}
err = mpr.Parse()
@ -216,9 +219,6 @@ func (i *T) parseMultipart(req http.Request) error {
component, exist := mpr.Data[name]
if !exist {
if !param.Optional {
return fmt.Errorf("%s: %w", name, ErrMissingRequiredParam)
}
continue
}