forked from go-rod/rod
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathutils.go
94 lines (81 loc) · 2.18 KB
/
utils.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
package rod
import (
"context"
"encoding/json"
"fmt"
"path/filepath"
"regexp"
"time"
"github.com/ysmood/kit"
"github.com/ysmood/rod/lib/cdp"
"github.com/ysmood/rod/lib/proto"
)
// Array of any type
type Array []interface{}
// SprintFnApply is a helper to render template into js code
// js looks like "(a, b) => {}", the a and b are the params passed into the function
func sprintFnApply(js string, params Array) string {
const tpl = `(%s).apply(this, %s)`
return fmt.Sprintf(tpl, js, kit.MustToJSON(params))
}
// SprintFnThis wrap js with this
func SprintFnThis(js string) string {
return fmt.Sprintf(`function() { return (%s).apply(this, arguments) }`, js)
}
// CancelPanic graceful panic
func CancelPanic(err error) {
if err != nil && err != context.Canceled {
panic(err)
}
}
// Event helps to convert a cdp.Event to proto.Event. Returns false if the convertion fails
func Event(msg *cdp.Event, evt proto.Event) bool {
if msg.Method == evt.MethodName() {
err := json.Unmarshal(msg.Params, evt)
return err == nil
}
return false
}
// NewEventFilter creates a event filter, when matches it will load data into the event object
func NewEventFilter(event proto.Event) EventFilter {
return func(e *cdp.Event) bool {
if event.MethodName() == e.Method {
kit.E(json.Unmarshal(e.Params, event))
return true
}
return false
}
}
func isNilContextErr(err error) bool {
if err == nil {
return false
}
cdpErr, ok := err.(*cdp.Error)
return ok && cdpErr.Code == -32000
}
func matchWithFilter(s string, includes, excludes []string) bool {
for _, include := range includes {
if regexp.MustCompile(include).MatchString(s) {
for _, exclude := range excludes {
if regexp.MustCompile(exclude).MatchString(s) {
return false
}
}
return true
}
}
return false
}
func saveScreenshot(bin []byte, toFile []string) {
if len(toFile) == 0 {
return
}
if toFile[0] == "" {
toFile = []string{"tmp", "screenshots", fmt.Sprintf("%d", time.Now().UnixNano()) + ".png"}
}
kit.E(kit.OutputFile(filepath.Join(toFile...), bin, nil))
}
func ginHTML(ctx kit.GinContext, body string) {
ctx.Header("Content-Type", "text/html; charset=utf-8")
kit.E(ctx.Writer.WriteString(body))
}