...

Source file src/github.com/PaesslerAG/gval/example_test.go

Documentation: github.com/PaesslerAG/gval

     1  package gval_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strings"
     7  	"time"
     8  
     9  	"github.com/PaesslerAG/gval"
    10  	"github.com/PaesslerAG/jsonpath"
    11  )
    12  
    13  func Example() {
    14  
    15  	vars := map[string]interface{}{"name": "World"}
    16  
    17  	value, err := gval.Evaluate(`"Hello " + name + "!"`, vars)
    18  	if err != nil {
    19  		fmt.Println(err)
    20  	}
    21  
    22  	fmt.Print(value)
    23  
    24  	// Output:
    25  	// Hello World!
    26  }
    27  
    28  func ExampleEvaluate() {
    29  
    30  	value, err := gval.Evaluate("foo > 0", map[string]interface{}{
    31  		"foo": -1.,
    32  	})
    33  	if err != nil {
    34  		fmt.Println(err)
    35  	}
    36  
    37  	fmt.Print(value)
    38  
    39  	// Output:
    40  	// false
    41  }
    42  
    43  func ExampleEvaluate_nestedParameter() {
    44  
    45  	value, err := gval.Evaluate("foo.bar > 0", map[string]interface{}{
    46  		"foo": map[string]interface{}{"bar": -1.},
    47  	})
    48  	if err != nil {
    49  		fmt.Println(err)
    50  	}
    51  
    52  	fmt.Print(value)
    53  
    54  	// Output:
    55  	// false
    56  }
    57  
    58  func ExampleEvaluate_array() {
    59  
    60  	value, err := gval.Evaluate("foo[0]", map[string]interface{}{
    61  		"foo": []interface{}{-1.},
    62  	})
    63  	if err != nil {
    64  		fmt.Println(err)
    65  	}
    66  
    67  	fmt.Print(value)
    68  
    69  	// Output:
    70  	// -1
    71  }
    72  
    73  func ExampleEvaluate_complexAccessor() {
    74  
    75  	value, err := gval.Evaluate(`foo["b" + "a" + "r"]`, map[string]interface{}{
    76  		"foo": map[string]interface{}{"bar": -1.},
    77  	})
    78  	if err != nil {
    79  		fmt.Println(err)
    80  	}
    81  
    82  	fmt.Print(value)
    83  
    84  	// Output:
    85  	// -1
    86  }
    87  
    88  func ExampleEvaluate_arithmetic() {
    89  
    90  	value, err := gval.Evaluate("(requests_made * requests_succeeded / 100) >= 90",
    91  		map[string]interface{}{
    92  			"requests_made":      100,
    93  			"requests_succeeded": 80,
    94  		})
    95  	if err != nil {
    96  		fmt.Println(err)
    97  	}
    98  
    99  	fmt.Print(value)
   100  
   101  	// Output:
   102  	// false
   103  }
   104  
   105  func ExampleEvaluate_string() {
   106  
   107  	value, err := gval.Evaluate(`http_response_body == "service is ok"`,
   108  		map[string]interface{}{
   109  			"http_response_body": "service is ok",
   110  		})
   111  	if err != nil {
   112  		fmt.Println(err)
   113  	}
   114  
   115  	fmt.Print(value)
   116  
   117  	// Output:
   118  	// true
   119  }
   120  
   121  func ExampleEvaluate_float64() {
   122  
   123  	value, err := gval.Evaluate("(mem_used / total_mem) * 100",
   124  		map[string]interface{}{
   125  			"total_mem": 1024,
   126  			"mem_used":  512,
   127  		})
   128  	if err != nil {
   129  		fmt.Println(err)
   130  	}
   131  
   132  	fmt.Print(value)
   133  
   134  	// Output:
   135  	// 50
   136  }
   137  
   138  func ExampleEvaluate_dateComparison() {
   139  
   140  	value, err := gval.Evaluate("date(`2014-01-02`) > date(`2014-01-01 23:59:59`)",
   141  		nil,
   142  		// define Date comparison because it is not part expression language gval
   143  		gval.InfixOperator(">", func(a, b interface{}) (interface{}, error) {
   144  			date1, ok1 := a.(time.Time)
   145  			date2, ok2 := b.(time.Time)
   146  
   147  			if ok1 && ok2 {
   148  				return date1.After(date2), nil
   149  			}
   150  			return nil, fmt.Errorf("unexpected operands types (%T) > (%T)", a, b)
   151  		}),
   152  	)
   153  	if err != nil {
   154  		fmt.Println(err)
   155  	}
   156  
   157  	fmt.Print(value)
   158  
   159  	// Output:
   160  	// true
   161  }
   162  
   163  func ExampleEvaluable() {
   164  	eval, err := gval.Full(gval.Constant("maximum_time", 52)).
   165  		NewEvaluable("response_time <= maximum_time")
   166  	if err != nil {
   167  		fmt.Println(err)
   168  	}
   169  
   170  	for i := 50; i < 55; i++ {
   171  		value, err := eval(context.Background(), map[string]interface{}{
   172  			"response_time": i,
   173  		})
   174  		if err != nil {
   175  			fmt.Println(err)
   176  
   177  		}
   178  
   179  		fmt.Println(value)
   180  	}
   181  
   182  	// Output:
   183  	// true
   184  	// true
   185  	// true
   186  	// false
   187  	// false
   188  }
   189  
   190  func ExampleEvaluate_strlen() {
   191  
   192  	value, err := gval.Evaluate(`strlen("someReallyLongInputString") <= 16`,
   193  		nil,
   194  		gval.Function("strlen", func(args ...interface{}) (interface{}, error) {
   195  			length := len(args[0].(string))
   196  			return (float64)(length), nil
   197  		}))
   198  	if err != nil {
   199  		fmt.Println(err)
   200  	}
   201  
   202  	fmt.Print(value)
   203  
   204  	// Output:
   205  	// false
   206  }
   207  
   208  func ExampleEvaluate_encoding() {
   209  
   210  	value, err := gval.Evaluate(`(7 < "47" == true ? "hello world!\n\u263a" : "good bye\n")`+" + ` more text`",
   211  		nil,
   212  		gval.Function("strlen", func(args ...interface{}) (interface{}, error) {
   213  			length := len(args[0].(string))
   214  			return (float64)(length), nil
   215  		}))
   216  	if err != nil {
   217  		fmt.Println(err)
   218  	}
   219  
   220  	fmt.Print(value)
   221  
   222  	// Output:
   223  	// hello world!
   224  	// ☺ more text
   225  }
   226  
   227  type exampleType struct {
   228  	Hello string
   229  }
   230  
   231  func (e exampleType) World() string {
   232  	return "world"
   233  }
   234  
   235  func ExampleEvaluate_accessor() {
   236  
   237  	value, err := gval.Evaluate(`foo.Hello + foo.World()`,
   238  		map[string]interface{}{
   239  			"foo": exampleType{Hello: "hello "},
   240  		})
   241  	if err != nil {
   242  		fmt.Println(err)
   243  	}
   244  
   245  	fmt.Print(value)
   246  
   247  	// Output:
   248  	// hello world
   249  }
   250  
   251  func ExampleEvaluate_flatAccessor() {
   252  
   253  	value, err := gval.Evaluate(`Hello + World()`,
   254  		exampleType{Hello: "hello "},
   255  	)
   256  	if err != nil {
   257  		fmt.Println(err)
   258  	}
   259  
   260  	fmt.Print(value)
   261  
   262  	// Output:
   263  	// hello world
   264  }
   265  
   266  func ExampleEvaluate_nestedAccessor() {
   267  
   268  	value, err := gval.Evaluate(`foo.Bar.Hello + foo.Bar.World()`,
   269  		map[string]interface{}{
   270  			"foo": struct{ Bar exampleType }{
   271  				Bar: exampleType{Hello: "hello "},
   272  			},
   273  		})
   274  	if err != nil {
   275  		fmt.Println(err)
   276  	}
   277  
   278  	fmt.Print(value)
   279  
   280  	// Output:
   281  	// hello world
   282  }
   283  
   284  func ExampleVariableSelector() {
   285  	value, err := gval.Evaluate(`hello.world`,
   286  		"!",
   287  		gval.VariableSelector(func(path gval.Evaluables) gval.Evaluable {
   288  			return func(c context.Context, v interface{}) (interface{}, error) {
   289  				keys, err := path.EvalStrings(c, v)
   290  				if err != nil {
   291  					return nil, err
   292  				}
   293  				return fmt.Sprintf("%s%s", strings.Join(keys, " "), v), nil
   294  			}
   295  		}),
   296  	)
   297  	if err != nil {
   298  		fmt.Println(err)
   299  	}
   300  
   301  	fmt.Print(value)
   302  
   303  	// Output:
   304  	// hello world!
   305  }
   306  
   307  func ExampleEvaluable_EvalInt() {
   308  	eval, err := gval.Full().NewEvaluable("1 + x")
   309  	if err != nil {
   310  		fmt.Println(err)
   311  		return
   312  	}
   313  
   314  	value, err := eval.EvalInt(context.Background(), map[string]interface{}{"x": 5})
   315  	if err != nil {
   316  		fmt.Println(err)
   317  	}
   318  
   319  	fmt.Print(value)
   320  
   321  	// Output:
   322  	// 6
   323  }
   324  
   325  func ExampleEvaluable_EvalBool() {
   326  	eval, err := gval.Full().NewEvaluable("1 == x")
   327  	if err != nil {
   328  		fmt.Println(err)
   329  		return
   330  	}
   331  
   332  	value, err := eval.EvalBool(context.Background(), map[string]interface{}{"x": 1})
   333  	if err != nil {
   334  		fmt.Println(err)
   335  	}
   336  
   337  	if value {
   338  		fmt.Print("yeah")
   339  	}
   340  
   341  	// Output:
   342  	// yeah
   343  }
   344  
   345  func ExampleEvaluate_jsonpath() {
   346  
   347  	value, err := gval.Evaluate(`$["response-time"]`,
   348  		map[string]interface{}{
   349  			"response-time": 100,
   350  		},
   351  		jsonpath.Language(),
   352  	)
   353  	if err != nil {
   354  		fmt.Println(err)
   355  	}
   356  
   357  	fmt.Print(value)
   358  
   359  	// Output:
   360  	// 100
   361  }
   362  
   363  func ExampleLanguage() {
   364  	lang := gval.NewLanguage(gval.JSON(), gval.Arithmetic(),
   365  		//pipe operator
   366  		gval.PostfixOperator("|", func(c context.Context, p *gval.Parser, pre gval.Evaluable) (gval.Evaluable, error) {
   367  			post, err := p.ParseExpression(c)
   368  			if err != nil {
   369  				return nil, err
   370  			}
   371  			return func(c context.Context, v interface{}) (interface{}, error) {
   372  				v, err := pre(c, v)
   373  				if err != nil {
   374  					return nil, err
   375  				}
   376  				return post(c, v)
   377  			}, nil
   378  		}))
   379  
   380  	eval, err := lang.NewEvaluable(`{"foobar": 50} | foobar + 100`)
   381  	if err != nil {
   382  		fmt.Println(err)
   383  	}
   384  
   385  	value, err := eval(context.Background(), nil)
   386  
   387  	if err != nil {
   388  		fmt.Println(err)
   389  	}
   390  
   391  	fmt.Println(value)
   392  
   393  	// Output:
   394  	// 150
   395  }
   396  
   397  type exampleCustomSelector struct{ hidden string }
   398  
   399  var _ gval.Selector = &exampleCustomSelector{}
   400  
   401  func (s *exampleCustomSelector) SelectGVal(ctx context.Context, k string) (interface{}, error) {
   402  	if k == "hidden" {
   403  		return s.hidden, nil
   404  	}
   405  
   406  	return nil, nil
   407  }
   408  
   409  func ExampleSelector() {
   410  	lang := gval.Base()
   411  	value, err := lang.Evaluate(
   412  		"myStruct.hidden",
   413  		map[string]interface{}{"myStruct": &exampleCustomSelector{hidden: "hello world"}},
   414  	)
   415  
   416  	if err != nil {
   417  		fmt.Println(err)
   418  	}
   419  
   420  	fmt.Println(value)
   421  
   422  	// Output:
   423  	// hello world
   424  }
   425  
   426  func parseSub(ctx context.Context, p *gval.Parser) (gval.Evaluable, error) {
   427  	return p.ParseSublanguage(ctx, subLang)
   428  }
   429  
   430  var (
   431  	superLang = gval.NewLanguage(
   432  		gval.PrefixExtension('$', parseSub),
   433  	)
   434  	subLang = gval.NewLanguage(
   435  		gval.Init(func(ctx context.Context, p *gval.Parser) (gval.Evaluable, error) { return p.Const("hello world"), nil }),
   436  	)
   437  )
   438  
   439  func ExampleParser_ParseSublanguage() {
   440  	value, err := superLang.Evaluate("$", nil)
   441  
   442  	if err != nil {
   443  		fmt.Println(err)
   444  	}
   445  
   446  	fmt.Println(value)
   447  
   448  	// Output:
   449  	// hello world
   450  }
   451  

View as plain text