Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AddOperation ¶
AddOperation to the default JSONLogic
func Apply ¶
func Apply(rule interface{}, data interface{}) (interface{}, error)
Apply rule on data using the default JSONLogic
Example ¶
package main
import (
"encoding/json"
"fmt"
"github.com/HuanTeng/go-jsonlogic"
)
func main() {
var rule, data interface{}
json.Unmarshal([]byte(`
{"if" : [
{"<": [{"var":"temp"}, 0] }, "freezing",
{"<": [{"var":"temp"}, 100] }, "liquid",
"gas"
]}`), &rule)
json.Unmarshal([]byte(`{"temp":55}`), &data)
got, err := jsonlogic.Apply(rule, data)
if err != nil {
// handle error
}
fmt.Println(got)
}
Output: liquid
Types ¶
type LogicApplier ¶
type LogicApplier interface {
Apply(rule interface{}, data interface{}) (interface{}, error)
AddOperation(symbol string, op Operator) error
Validate(rule interface{}) error
}
LogicApplier can apply logic(rule) on data, based on defined operations
func NewEmptyLogic ¶
func NewEmptyLogic() LogicApplier
NewEmptyLogic makes an empty LogicApplier without operators
func NewJSONLogic ¶
func NewJSONLogic() LogicApplier
NewJSONLogic makes a new LogicApplier with default jsonlogic operators
type Operator ¶
type Operator interface {
Operate(applier LogicApplier, data DataType, params []RuleType) (DataType, error)
}
Operator is an interface that can be added to LogicApplier
Example ¶
package main
import (
"encoding/json"
"errors"
"fmt"
"github.com/HuanTeng/go-jsonlogic"
)
// gcd operator
type gcd struct{}
// Operate implements `jsonlogic.Operator`
func (gcd) Operate(applier jsonlogic.LogicApplier, data jsonlogic.DataType, params []jsonlogic.RuleType) (jsonlogic.DataType, error) {
if len(params) != 2 {
return nil, errors.New("only support 2 params")
}
var (
p0, p1 interface{}
err error
)
// apply jsonlogic to each parameters recursively
if p0, err = applier.Apply(params[0], data); err != nil {
return nil, err
}
if p1, err = applier.Apply(params[1], data); err != nil {
return nil, err
}
p0f, ok0 := p0.(float64)
p1f, ok1 := p1.(float64)
if !ok0 || !ok1 {
return nil, errors.New("params should be numbers")
}
// recursive GCD function
var gcdFunc func(a int, b int) int
gcdFunc = func(a int, b int) int {
if b == 0 {
return a
}
return gcdFunc(b, a%b)
}
out := gcdFunc(int(p0f), int(p1f))
// to output a number, always use float64
return float64(out), nil
}
func main() {
jl := jsonlogic.NewJSONLogic()
jl.AddOperation("gcd", gcd{})
var rule interface{}
json.Unmarshal([]byte(`{"gcd": [{"+": [14, 1]}, 25]}`), &rule)
got, err := jl.Apply(rule, nil)
if err != nil {
// handle error
}
fmt.Println(got)
}
Output: 5