github.com/bytedance/go-tagexpr@v2.7.5-0.20210114074101-de5b8743ad85+incompatible/example_test.go (about)

     1  // Copyright 2019 Bytedance Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package tagexpr_test
    16  
    17  import (
    18  	"fmt"
    19  
    20  	tagexpr "github.com/bytedance/go-tagexpr"
    21  )
    22  
    23  func Example() {
    24  	type T struct {
    25  		A  int             `tagexpr:"$<0||$>=100"`
    26  		B  string          `tagexpr:"len($)>1 && regexp('^\\w*$')"`
    27  		C  bool            `tagexpr:"expr1:(f.g)$>0 && $; expr2:'C must be true when T.f.g>0'"`
    28  		d  []string        `tagexpr:"@:len($)>0 && $[0]=='D'; msg:sprintf('invalid d: %v',$)"`
    29  		e  map[string]int  `tagexpr:"len($)==$['len']"`
    30  		e2 map[string]*int `tagexpr:"len($)==$['len']"`
    31  		f  struct {
    32  			g int `tagexpr:"$"`
    33  		}
    34  	}
    35  
    36  	vm := tagexpr.New("tagexpr")
    37  	t := &T{
    38  		A:  107,
    39  		B:  "abc",
    40  		C:  true,
    41  		d:  []string{"x", "y"},
    42  		e:  map[string]int{"len": 1},
    43  		e2: map[string]*int{"len": new(int)},
    44  		f: struct {
    45  			g int `tagexpr:"$"`
    46  		}{1},
    47  	}
    48  
    49  	tagExpr, err := vm.Run(t)
    50  	if err != nil {
    51  		panic(err)
    52  	}
    53  
    54  	fmt.Println(tagExpr.Eval("A"))
    55  	fmt.Println(tagExpr.Eval("B"))
    56  	fmt.Println(tagExpr.Eval("C@expr1"))
    57  	fmt.Println(tagExpr.Eval("C@expr2"))
    58  	if !tagExpr.Eval("d").(bool) {
    59  		fmt.Println(tagExpr.Eval("d@msg"))
    60  	}
    61  	fmt.Println(tagExpr.Eval("e"))
    62  	fmt.Println(tagExpr.Eval("e2"))
    63  	fmt.Println(tagExpr.Eval("f.g"))
    64  
    65  	// Output:
    66  	// true
    67  	// true
    68  	// true
    69  	// C must be true when T.f.g>0
    70  	// invalid d: [x y]
    71  	// true
    72  	// false
    73  	// 1
    74  }