Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Can not eval map[string] interface properly #325

Unanswered
scorpinxia asked this question in Q&A
Discussion options

I have run some test like TEST1,I want the error happened( variables have no cpu1 field),but It just return false

Also I do test like TEST2 , just change field 'cpu1' to 'request1' , It works (it return err , can not fetch cpu from nil )

again I do test like TEST3 , just change '==' to '>' , It works (it return err invalid operation: < float64 (1:27))

any ideas?

  1. TEST1

     `{
     	name: "number expr",
     	matchExpr: "test.hello.request.cpu1 == 0.15",
     	variables: map[string]interface{}{
     		"test": map[string]interface{}{
     			"hello": map[string]interface{}{
     				"request": map[string]interface{}{
     					"cpu": 0.2,
     				},
     			},
     		},
     	},
     },`
    
  2. TEST2

     `{
     	name: "number expr",
     	matchExpr: "test.hello.request1.cpu == 0.15",
     	variables: map[string]interface{}{
     		"test": map[string]interface{}{
     			"hello": map[string]interface{}{
     				"request": map[string]interface{}{
     					"cpu": 0.2,
     				},
     			},
     		},
     	},
     },`
    
  3. TEST3

     `{
     	name: "number expr",
     	matchExpr: "test.hello.request.cpu1 < 0.15",
     	variables: map[string]interface{}{
     		"test": map[string]interface{}{
     			"hello": map[string]interface{}{
     				"request": map[string]interface{}{
     					"cpu": 0.2,
     				},
     			},
     		},
     	},
     },`
    
  4. Eval expression code

func MatchExprEval(matchExpr string, variables map[string]interface{}) (bool, error) {
	program, err := expr.Compile(matchExpr, expr.Env(variables), expr.AsBool())
	if err != nil {
		return false, err
	}
	output, err := expr.Run(program, variables)
	if err != nil {
		return false, err
	}
	var outputBool, ok bool
	if outputBool, ok = output.(bool); !ok {
		return false, fmt.Errorf("not a bool result")
	}
	return outputBool, nil
}
You must be logged in to vote

Replies: 0 comments

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
1 participant
Converted from issue

This discussion was converted from issue #324 on January 30, 2023 11:07.

AltStyle によって変換されたページ (->オリジナル) /