Exemplo n.º 1
0
// Parse parses rules expressions
func (r *Rules) Parse(expression string) (*mux.Route, error) {
	var resultRoute *mux.Route
	err := r.parseRules(expression, func(functionName string, function interface{}, arguments []string) error {
		inputs := make([]reflect.Value, len(arguments))
		for i := range arguments {
			inputs[i] = reflect.ValueOf(arguments[i])
		}
		method := reflect.ValueOf(function)
		if method.IsValid() {
			resultRoute = method.Call(inputs)[0].Interface().(*mux.Route)
			if r.err != nil {
				return r.err
			}
			if resultRoute.GetError() != nil {
				return resultRoute.GetError()
			}

		} else {
			return errors.New("Method not found: '" + functionName + "'")
		}
		return nil
	})
	if err != nil {
		return nil, fmt.Errorf("Error parsing rule: %v", err)
	}
	return resultRoute, nil
}
Exemplo n.º 2
0
// Parse parses rules expressions
func (r *Rules) Parse(expression string) (*mux.Route, error) {
	functions := map[string]interface{}{
		"Host":            r.host,
		"HostRegexp":      r.hostRegexp,
		"Path":            r.path,
		"PathStrip":       r.pathStrip,
		"PathPrefix":      r.pathPrefix,
		"PathPrefixStrip": r.pathPrefixStrip,
		"Method":          r.methods,
		"Headers":         r.headers,
		"HeadersRegexp":   r.headersRegexp,
	}
	f := func(c rune) bool {
		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
		parsedFunctions := strings.FieldsFunc(rule, f)
		if len(parsedFunctions) == 0 {
			return nil, errors.New("Error parsing rule: " + rule)
		}
		parsedFunction, ok := functions[parsedFunctions[0]]
		if !ok {
			return nil, errors.New("Error parsing rule: " + rule + ". Unknown function: " + parsedFunctions[0])
		}
		parsedFunctions = append(parsedFunctions[:0], parsedFunctions[1:]...)
		fargs := func(c rune) bool {
			return c == ','
		}
		// get function
		parsedArgs := strings.FieldsFunc(strings.Join(parsedFunctions, ":"), fargs)
		if len(parsedArgs) == 0 {
			return nil, errors.New("Error parsing args from rule: " + rule)
		}

		inputs := make([]reflect.Value, len(parsedArgs))
		for i := range parsedArgs {
			inputs[i] = reflect.ValueOf(parsedArgs[i])
		}
		method := reflect.ValueOf(parsedFunction)
		if method.IsValid() {
			resultRoute = method.Call(inputs)[0].Interface().(*mux.Route)
			if r.err != nil {
				return nil, r.err
			}
			if resultRoute.GetError() != nil {
				return nil, resultRoute.GetError()
			}

		} else {
			return nil, errors.New("Method not found: " + parsedFunctions[0])
		}
	}
	return resultRoute, nil
}