PaesslerAG / gval

Expression evaluation in golang
BSD 3-Clause "New" or "Revised" License
713 stars 83 forks source link

Passing a context to the custom functions #76

Closed schneekatze closed 2 years ago

schneekatze commented 2 years ago

Hello guys,

at the moment if we want to define a custom function, we just extend the language

gval.Evaluate(
    expression,
    data,
    gval.Function("foo", func(args ...interface{}) (interface{}, error) {
        return "bar", nil
    }),
   ...
)

Yet we can EvaluateWithContext, say context with value.

ctx := context.WithValue(context.Background(), "input", data)
gval.EvaluateWithContext(
    ctx,
    expression,
    data,
    gval.Function("foo", func(args ...interface{}) (interface{}, error) {
        return "bar", nil
    }),
   ...
)

Unfortunately, the context is not passed into a function itself. So maybe, we could do something like

ctx := context.WithValue(context.Background(), "input", data)
gval.EvaluateWithContext(
    ctx,
    expression,
    data,
    gval.FunctionWithContext("foo", func(ctx context.Context, args ...interface{}) (interface{}, error) {
        return count(ctx.Value("input")), nil
    }),
   ...
)

Why would one need it? E.g.:

Wdyt? Or maybe there's already the way to pass some extra information into the gval function? I've tried with Init, but I apparently don't understand its concept that much.

Best regards, sk

schneekatze commented 2 years ago

It's already there