refactor parameter check

This commit is contained in:
Adrien Marquès 2018-05-29 19:01:20 +02:00
parent fdf036d366
commit edf2cdf755
1 changed files with 44 additions and 33 deletions

View File

@ -69,59 +69,67 @@ func (s *Server) route(res http.ResponseWriter, req *http.Request) {
return
}
/* (4) Check arguments
/* (4) Check parameters
---------------------------------------------------------*/
var paramError Err = ErrSuccess
parameters := make(map[string]interface{})
for name, param := range method.Parameters {
fmt.Printf("- parameter '%s'\n", name)
/* (1) Extract value */
p, isset := request.Data.Set[name]
/* (2) OPTIONAL ? */
if !isset {
// fail if required
if !*param.Optional {
fmt.Printf(" - required and missing\n")
/* (2) Required & missing */
if !isset && !*param.Optional {
paramError = ErrMissingParam
paramError.BindArgument(name)
break
}
// error if default param is nil
} else if param.Default == nil {
fmt.Printf(" - required and no default\n")
paramError = ErrInvalidDefaultParam
paramError.BindArgument(name)
break
// set default p if optional
} else {
fmt.Printf(" - default value: '%v'\n", *param.Default)
/* (3) Optional & missing: set default value */
if !isset {
p = &RequestParameter{
Parsed: true,
Value: *param.Default,
File: param.Type == "FILE",
Value: nil,
}
if param.Default != nil {
p.Value = *param.Default
}
}
}
/* (3) Parse parameter variable */
/* (4) Parse parameter if not file */
if !p.Parsed && !p.File {
p.Value = parseHttpData(p.Value)
}
/* (4) Check type */
isValid := s.Checker.Run(param.Type, p.Value)
fmt.Printf(" - valid: %t\n", isValid == nil)
if isValid != nil {
/* (4) Fail on unexpected multipart file */
waitFile, gotFile := param.Type == "FILE", p.File
if gotFile && !waitFile || !gotFile && waitFile {
paramError = ErrInvalidParam
paramError.BindArgument(name)
paramError.BindArgument("FILE")
break
}
/* (5) Do not check if file */
if gotFile {
parameters[name] = p.Value
continue
}
/* (6) Check type */
if s.Checker.Run(param.Type, p.Value) != nil {
paramError = ErrInvalidParam
paramError.BindArgument(name)
paramError.BindArgument(param.Type)
paramError.BindArgument(p.Value)
break
}
parameters[name] = p.Value
}
fmt.Printf("\n")
@ -135,5 +143,8 @@ func (s *Server) route(res http.ResponseWriter, req *http.Request) {
}
fmt.Printf("OK\nplugin: '%si.so'\n", strings.Join(request.ControllerUri, "/"))
for name, value := range parameters {
fmt.Printf(" $%s = %v\n", name, value)
}
return
}