2018-09-18 16:42:38 -04:00
|
|
|
package driver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2018-09-23 04:33:20 -04:00
|
|
|
"fmt"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
2018-09-18 16:42:38 -04:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
2018-09-26 22:03:06 -04:00
|
|
|
"github.com/MontFerret/ferret/pkg/stdlib/html/driver/dynamic"
|
|
|
|
"github.com/MontFerret/ferret/pkg/stdlib/html/driver/static"
|
2018-09-18 16:42:38 -04:00
|
|
|
)
|
|
|
|
|
2018-10-06 22:33:39 -04:00
|
|
|
type Name string
|
2018-09-26 22:03:06 -04:00
|
|
|
|
|
|
|
const (
|
2018-10-06 22:33:39 -04:00
|
|
|
Dynamic Name = "dynamic"
|
|
|
|
Static Name = "static"
|
2018-09-26 22:03:06 -04:00
|
|
|
)
|
2018-09-18 16:42:38 -04:00
|
|
|
|
|
|
|
type Driver interface {
|
2018-10-06 22:33:39 -04:00
|
|
|
GetDocument(ctx context.Context, url values.String) (values.HTMLNode, error)
|
2018-09-18 16:42:38 -04:00
|
|
|
Close() error
|
|
|
|
}
|
|
|
|
|
2018-10-06 22:33:39 -04:00
|
|
|
func ToContext(ctx context.Context, name Name, drv Driver) context.Context {
|
2018-09-18 16:42:38 -04:00
|
|
|
return context.WithValue(ctx, name, drv)
|
|
|
|
}
|
|
|
|
|
2018-10-06 22:33:39 -04:00
|
|
|
func FromContext(ctx context.Context, name Name) (Driver, error) {
|
2018-09-18 16:42:38 -04:00
|
|
|
val := ctx.Value(name)
|
|
|
|
|
|
|
|
drv, ok := val.(Driver)
|
|
|
|
|
|
|
|
if ok {
|
2018-09-23 04:33:20 -04:00
|
|
|
return drv, nil
|
2018-09-18 16:42:38 -04:00
|
|
|
}
|
|
|
|
|
2018-09-23 04:33:20 -04:00
|
|
|
return nil, core.Error(core.ErrNotFound, fmt.Sprintf("%s driver", name))
|
2018-09-18 16:42:38 -04:00
|
|
|
}
|
|
|
|
|
2018-09-26 22:03:06 -04:00
|
|
|
func WithDynamicDriver(ctx context.Context, addr string) context.Context {
|
|
|
|
return context.WithValue(ctx, Dynamic, dynamic.NewDriver(addr))
|
2018-09-18 16:42:38 -04:00
|
|
|
}
|
|
|
|
|
2018-09-26 22:03:06 -04:00
|
|
|
func WithStaticDriver(ctx context.Context, opts ...static.Option) context.Context {
|
|
|
|
return context.WithValue(ctx, Static, static.NewDriver(opts...))
|
2018-09-18 16:42:38 -04:00
|
|
|
}
|