1
0
mirror of https://github.com/MontFerret/ferret.git synced 2024-12-16 11:37:36 +02:00
ferret/pkg/runtime/program.go

60 lines
1.1 KiB
Go
Raw Normal View History

2018-09-18 22:42:38 +02:00
package runtime
import (
"context"
"github.com/MontFerret/ferret/pkg/html"
2018-09-18 22:42:38 +02:00
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
)
type Program struct {
2018-09-28 06:28:33 +02:00
src string
body core.Expression
2018-09-18 22:42:38 +02:00
}
2018-09-28 06:28:33 +02:00
func NewProgram(src string, body core.Expression) (*Program, error) {
if src == "" {
return nil, core.Error(core.ErrMissedArgument, "source")
}
2018-10-28 07:45:26 +02:00
if body == nil {
2018-09-28 06:28:33 +02:00
return nil, core.Error(core.ErrMissedArgument, "body")
}
return &Program{src, body}, nil
}
func (p *Program) Source() string {
return p.src
2018-09-18 22:42:38 +02:00
}
func (p *Program) Run(ctx context.Context, setters ...Option) ([]byte, error) {
scope, closeFn := core.NewRootScope()
defer closeFn()
2018-10-18 04:57:36 +02:00
ctx = NewOptions().Apply(setters...).WithContext(ctx)
ctx = html.WithDynamicDriver(ctx)
ctx = html.WithStaticDriver(ctx)
2018-09-18 22:42:38 +02:00
2018-09-28 06:28:33 +02:00
out, err := p.body.Exec(ctx, scope)
2018-09-18 22:42:38 +02:00
if err != nil {
js, _ := values.None.MarshalJSON()
return js, err
}
return out.MarshalJSON()
}
2018-09-28 04:10:17 +02:00
func (p *Program) MustRun(ctx context.Context, setters ...Option) []byte {
out, err := p.Run(ctx, setters...)
if err != nil {
panic(err)
}
return out
}