/
helpers.go
106 lines (89 loc) · 2.15 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package drivers
import (
"github.com/MontFerret/ferret/pkg/runtime/core"
"github.com/MontFerret/ferret/pkg/runtime/values"
"github.com/MontFerret/ferret/pkg/runtime/values/types"
)
func ToPage(value core.Value) (HTMLPage, error) {
err := core.ValidateType(value, HTMLPageType)
if err != nil {
return nil, err
}
return value.(HTMLPage), nil
}
func ToDocument(value core.Value) (HTMLDocument, error) {
switch v := value.(type) {
case HTMLPage:
return v.GetMainFrame(), nil
case HTMLDocument:
return v, nil
default:
return nil, core.TypeError(
value.Type(),
HTMLPageType,
HTMLDocumentType,
)
}
}
func ToElement(value core.Value) (HTMLElement, error) {
switch v := value.(type) {
case HTMLPage:
return v.GetMainFrame().GetElement(), nil
case HTMLDocument:
return v.GetElement(), nil
case HTMLElement:
return v, nil
default:
return nil, core.TypeError(
value.Type(),
HTMLPageType,
HTMLDocumentType,
HTMLElementType,
)
}
}
func ToQuerySelector(value core.Value) (QuerySelector, error) {
switch v := value.(type) {
case QuerySelector:
return v, nil
case values.String:
return NewCSSSelector(v), nil
default:
return QuerySelector{}, core.TypeError(value.Type(), types.String, QuerySelectorType)
}
}
func SetDefaultParams(opts *Options, params Params) Params {
if params.Headers == nil && opts.Headers != nil {
params.Headers = NewHTTPHeaders()
}
// set default headers
if opts.Headers != nil {
opts.Headers.ForEach(func(value []string, key string) bool {
val := params.Headers.Get(key)
// do not override user's set values
if val == "" {
params.Headers.SetArr(key, value)
}
return true
})
}
if params.Cookies == nil && opts.Cookies != nil {
params.Cookies = NewHTTPCookies()
}
// set default cookies
if opts.Cookies != nil {
opts.Cookies.ForEach(func(value HTTPCookie, key values.String) bool {
_, exists := params.Cookies.Get(key)
// do not override user's set values
if !exists {
params.Cookies.Set(value)
}
return true
})
}
// set default user agent
if opts.UserAgent != "" && params.UserAgent == "" {
params.UserAgent = opts.UserAgent
}
return params
}