All Projects → bytedance → Go Tagexpr

bytedance / Go Tagexpr

Licence: apache-2.0
An interesting go struct tag expression syntax for field validation, etc.

Programming Languages

go
31211 projects - #10 most used programming language
dsl
153 projects

Projects that are alternatives of or similar to Go Tagexpr

Input Mask Ios
User input masking library repo.
Stars: ✭ 494 (-38.79%)
Mutual labels:  validator
Nice Validator
Simple, smart and pleasant validation solution.
Stars: ✭ 587 (-27.26%)
Mutual labels:  validator
Devutils
🔥 ( 持续更新,目前含 160+ 工具类 ) DevUtils 是一个 Android 工具库,主要根据不同功能模块,封装快捷使用的工具类及 API 方法调用。该项目尽可能的便于开发人员,快捷、高效开发安全可靠的项目。
Stars: ✭ 680 (-15.74%)
Mutual labels:  validator
Iossampleapp
Sample iOS app demonstrating Coordinators, Dependency Injection, MVVM, Binding
Stars: ✭ 510 (-36.8%)
Mutual labels:  binding
Express Validator
An express.js middleware for validator.js.
Stars: ✭ 5,236 (+548.82%)
Mutual labels:  validator
Imgui Sfml
Dear ImGui binding for use with SFML
Stars: ✭ 596 (-26.15%)
Mutual labels:  binding
Store
Unidirectional, transactional, operation-based Store implementation.
Stars: ✭ 477 (-40.89%)
Mutual labels:  binding
Cel Go
Fast, portable, non-Turing complete expression evaluation with gradual typing (Go)
Stars: ✭ 720 (-10.78%)
Mutual labels:  expression
Gf
GoFrame is a modular, powerful, high-performance and enterprise-class application development framework of Golang.
Stars: ✭ 6,501 (+705.58%)
Mutual labels:  validator
Leveldown
Pure C++ Node.js LevelDB binding. An abstract-leveldown compliant store.
Stars: ✭ 678 (-15.99%)
Mutual labels:  binding
Oas Kit
Convert Swagger 2.0 definitions to OpenAPI 3.0 and resolve/validate/lint
Stars: ✭ 516 (-36.06%)
Mutual labels:  validator
Qtsharp
Mono/.NET bindings for Qt
Stars: ✭ 532 (-34.08%)
Mutual labels:  binding
Validation
The most awesome validation engine ever created for PHP
Stars: ✭ 5,484 (+579.55%)
Mutual labels:  validator
Pypostal
Python bindings to libpostal for fast international address parsing/normalization
Stars: ✭ 504 (-37.55%)
Mutual labels:  binding
Cimgui
c-api for imgui (https://github.com/ocornut/imgui) Look at: https://github.com/cimgui for other widgets
Stars: ✭ 707 (-12.39%)
Mutual labels:  binding
Validator.js
⁉️轻量级的 JavaScript 表单验证,字符串验证。没有依赖,支持 UMD ,~3kb。
Stars: ✭ 486 (-39.78%)
Mutual labels:  validator
Jsonpcallbackvalidator
JSONP callback validator.
Stars: ✭ 595 (-26.27%)
Mutual labels:  validator
Go Duktape
Duktape JavaScript engine bindings for Go
Stars: ✭ 747 (-7.43%)
Mutual labels:  binding
Swagger Parser
Swagger 2.0 and OpenAPI 3.0 parser/validator
Stars: ✭ 710 (-12.02%)
Mutual labels:  validator
Class Validator
Decorator-based property validation for classes.
Stars: ✭ 6,941 (+760.1%)
Mutual labels:  validator

go-tagexpr report card GoDoc

An interesting go struct tag expression syntax for field validation, etc.

Usage

  • Validator: A powerful validator that supports struct tag expression

  • Binding: A powerful HTTP request parameters binder that supports struct tag expression

Feature

  • Support for a variety of common operator
  • Support for accessing arrays, slices, members of the dictionary
  • Support access to any field in the current structure
  • Support access to nested fields, non-exported fields, etc.
  • Support registers function expression
  • Built-in len, sprintf, regexp functions
  • Support single mode and multiple mode to define expression
  • Parameter check subpackage
  • Use offset pointers to directly take values, better performance
  • Required go version ≥1.9

Example

package tagexpr_test

import (
	"fmt"

	tagexpr "github.com/bytedance/go-tagexpr/v2"
)

func Example() {
	type T struct {
		A  int             `tagexpr:"$<0||$>=100"`
		B  string          `tagexpr:"len($)>1 && regexp('^\\w*$')"`
		C  bool            `tagexpr:"expr1:(f.g)$>0 && $; expr2:'C must be true when T.f.g>0'"`
		d  []string        `tagexpr:"@:len($)>0 && $[0]=='D'; msg:sprintf('invalid d: %v',$)"`
		e  map[string]int  `tagexpr:"len($)==$['len']"`
		e2 map[string]*int `tagexpr:"len($)==$['len']"`
		f  struct {
			g int `tagexpr:"$"`
		}
	}

	vm := tagexpr.New("tagexpr")
	t := &T{
		A:  107,
		B:  "abc",
		C:  true,
		d:  []string{"x", "y"},
		e:  map[string]int{"len": 1},
		e2: map[string]*int{"len": new(int)},
		f: struct {
			g int `tagexpr:"$"`
		}{1},
	}

	tagExpr, err := vm.Run(t)
	if err != nil {
		panic(err)
	}

	fmt.Println(tagExpr.Eval("A"))
	fmt.Println(tagExpr.Eval("B"))
	fmt.Println(tagExpr.Eval("[email protected]"))
	fmt.Println(tagExpr.Eval("[email protected]"))
	if !tagExpr.Eval("d").(bool) {
		fmt.Println(tagExpr.Eval("[email protected]"))
	}
	fmt.Println(tagExpr.Eval("e"))
	fmt.Println(tagExpr.Eval("e2"))
	fmt.Println(tagExpr.Eval("f.g"))

	// Output:
	// true
	// true
	// true
	// C must be true when T.f.g>0
	// invalid d: [x y]
	// true
	// false
	// 1
}

Syntax

Struct tag syntax spec:

type T struct {
	// Single model
    Field1 T1 `tagName:"expression"`
	// Multiple model
    Field2 T2 `tagName:"exprName:expression; [exprName2:expression2;]..."`
	// Omit it
    Field3 T3 `tagName:"-"`
    // Omit it when it is nil
    Field4 T4 `tagName:"?"`
    ...
}

NOTE: The exprName under the same struct field cannot be the same!

Operator or Operand Explain
true false boolean
0 0.0 float64 "0"
'' String
\\' Escape ' delims in string
\" Escape " delims in string
nil nil, undefined
! not, suitable for bool, string, float64, nil, $ and ()
+ Digital addition or string splicing
- Digital subtraction or negative
* Digital multiplication
/ Digital division
% division remainder, as: float64(int64(a)%int64(b))
== eq
!= ne
> gt
>= ge
< lt
<= le
&& Logic and
|| Logic or
() Expression group
(X)$ Struct field value named X
(X.Y)$ Struct field value named X.Y
$ Shorthand for (X)$, omit (X) to indicate current struct field value
(X)$['A'] Map value with key A or struct A sub-field in the struct field X
(X)$[0] The 0th element or sub-field of the struct field X(type: map, slice, array, struct)
len((X)$) Built-in function len, the length of struct field X
mblen((X)$) the length of string field X (character number)
regexp('^\\w*$', (X)$) Regular match the struct field X, return boolean
regexp('^\\w*$') Regular match the current struct field, return boolean
sprintf('X value: %v', (X)$) fmt.Sprintf, format the value of struct field X

Operator priority(high -> low):

  • () ! bool float64 string nil
  • * / %
  • + -
  • < <= > >=
  • == !=
  • &&
  • ||

Field Selector

field_lv1.field_lv2...field_lvn

Expression Selector

  • If expression is single model or exprName is @:
field_lv1.field_lv2...field_lvn
  • If expression is multiple model and exprName is not @:
[email protected]

Benchmark

goos: darwin
goarch: amd64
pkg: github.com/bytedance/go-tagexpr
BenchmarkTagExpr-4   	10000000	       148 ns/op	      32 B/op	       3 allocs/op
BenchmarkReflect-4   	10000000	       182 ns/op	      16 B/op	       2 allocs/op
PASS

Go to test code

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].