allow multiple rules

This commit is contained in:
Fabrice CLAEYS 2016-06-06 09:21:00 +02:00
parent c5ac563e74
commit 84076db78e

View file

@ -109,23 +109,34 @@ func (r *Rules) Parse(expression string) (*mux.Route, error) {
f := func(c rune) bool { f := func(c rune) bool {
return c == ':' return c == ':'
} }
// Allow multiple rules separated by ;
splitRule := func(c rune) bool {
return c == ';'
}
parsedRules := strings.FieldsFunc(expression, splitRule)
var resultRoute *mux.Route
for _, rule := range parsedRules {
// get function // get function
parsedFunctions := strings.FieldsFunc(expression, f) parsedFunctions := strings.FieldsFunc(rule, f)
if len(parsedFunctions) == 0 { if len(parsedFunctions) == 0 {
return nil, errors.New("Error parsing rule: " + expression) return nil, errors.New("Error parsing rule: " + rule)
} }
parsedFunction, ok := functions[parsedFunctions[0]] parsedFunction, ok := functions[parsedFunctions[0]]
if !ok { if !ok {
return nil, errors.New("Error parsing rule: " + expression + ". Unknown function: " + parsedFunctions[0]) return nil, errors.New("Error parsing rule: " + rule + ". Unknown function: " + parsedFunctions[0])
} }
parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...) parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...)
fargs := func(c rune) bool { fargs := func(c rune) bool {
return c == ',' || c == ';' return c == ','
} }
// get function // get function
parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs) parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs)
if len(parsedArgs) == 0 { if len(parsedArgs) == 0 {
return nil, errors.New("Error parsing args from rule: " + expression) return nil, errors.New("Error parsing args from rule: " + rule)
} }
inputs := make([]reflect.Value, len(parsedArgs)) inputs := make([]reflect.Value, len(parsedArgs))
@ -134,14 +145,17 @@ func (r *Rules) Parse(expression string) (*mux.Route, error) {
} }
method := reflect.ValueOf(parsedFunction) method := reflect.ValueOf(parsedFunction)
if method.IsValid() { if method.IsValid() {
resultRoute := method.Call(inputs)[0].Interface().(*mux.Route) resultRoute = method.Call(inputs)[0].Interface().(*mux.Route)
if r.err != nil { if r.err != nil {
return nil, r.err return nil, r.err
} }
if resultRoute.GetError() != nil { if resultRoute.GetError() != nil {
return nil, resultRoute.GetError() return nil, resultRoute.GetError()
} }
return resultRoute, nil
} } else {
return nil, errors.New("Method not found: " + parsedFunctions[0]) return nil, errors.New("Method not found: " + parsedFunctions[0])
}
}
return resultRoute, nil
} }