2018-12-22 06:14:41 +02:00
|
|
|
package drivers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2019-02-13 19:31:18 +02:00
|
|
|
"io"
|
2019-02-21 04:24:05 +02:00
|
|
|
"time"
|
2019-02-13 19:31:18 +02:00
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/core"
|
|
|
|
"github.com/MontFerret/ferret/pkg/runtime/values"
|
|
|
|
)
|
|
|
|
|
2019-02-21 04:24:05 +02:00
|
|
|
const DefaultTimeout = time.Second * 30
|
|
|
|
|
2018-12-22 06:14:41 +02:00
|
|
|
type (
|
2019-02-20 01:10:18 +02:00
|
|
|
ctxKey struct{}
|
2018-12-22 06:14:41 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
ctxValue struct {
|
|
|
|
opts *options
|
|
|
|
drivers map[string]Driver
|
2018-12-22 06:14:41 +02:00
|
|
|
}
|
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
Driver interface {
|
2018-12-22 06:14:41 +02:00
|
|
|
io.Closer
|
2019-02-20 01:10:18 +02:00
|
|
|
Name() string
|
|
|
|
GetDocument(ctx context.Context, url values.String) (HTMLDocument, error)
|
2018-12-22 06:14:41 +02:00
|
|
|
}
|
|
|
|
)
|
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
func WithContext(ctx context.Context, drv Driver, opts ...Option) context.Context {
|
|
|
|
ctx, value := resolveValue(ctx)
|
2018-12-22 06:14:41 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
value.drivers[drv.Name()] = drv
|
2018-12-22 06:14:41 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
for _, opt := range opts {
|
|
|
|
opt(drv, value.opts)
|
2018-12-22 06:14:41 +02:00
|
|
|
}
|
|
|
|
|
2019-02-21 20:04:38 +02:00
|
|
|
// set first registered driver as a default one
|
|
|
|
if value.opts.defaultDriver == "" {
|
|
|
|
value.opts.defaultDriver = drv.Name()
|
|
|
|
}
|
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
return ctx
|
2018-12-22 06:14:41 +02:00
|
|
|
}
|
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
func FromContext(ctx context.Context, name string) (Driver, error) {
|
|
|
|
_, value := resolveValue(ctx)
|
2018-12-22 06:14:41 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
if name == "" {
|
|
|
|
name = value.opts.defaultDriver
|
|
|
|
}
|
2018-12-22 06:14:41 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
drv, exists := value.drivers[name]
|
|
|
|
|
|
|
|
if !exists {
|
|
|
|
return nil, core.Error(core.ErrNotFound, name)
|
2018-12-22 06:14:41 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return drv, nil
|
|
|
|
}
|
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
func resolveValue(ctx context.Context) (context.Context, *ctxValue) {
|
|
|
|
key := ctxKey{}
|
|
|
|
v := ctx.Value(key)
|
|
|
|
value, ok := v.(*ctxValue)
|
|
|
|
|
|
|
|
if !ok {
|
|
|
|
value = &ctxValue{
|
|
|
|
opts: &options{},
|
|
|
|
drivers: make(map[string]Driver),
|
|
|
|
}
|
|
|
|
|
|
|
|
return context.WithValue(ctx, key, value), value
|
|
|
|
}
|
2018-12-22 06:14:41 +02:00
|
|
|
|
2019-02-20 01:10:18 +02:00
|
|
|
return ctx, value
|
2018-12-22 06:14:41 +02:00
|
|
|
}
|