-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
112 lines (91 loc) · 2.39 KB
/
client.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
107
108
109
110
111
112
package chromeserverclient
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"github.com/function61/gokit/os/osutil"
"github.com/function61/gokit/net/http/ezhttp"
"github.com/function61/gokit/encoding/jsonfile"
)
type Output struct {
LogMessages []string `json:"logMessages"`
ErrorMessages []string `json:"errorMessages"`
Error *string `json:"error,omitempty"`
ErrorAutoScreenshotUrl *string `json:"errorAutoScreenshotUrl,omitempty"`
Data *json.RawMessage `json:"data,omitempty"`
}
const (
Function61 = "https://function61.com/api/chromeserver"
)
type AuthTokenObtainer func() (string, error)
type Options struct {
ErrorAutoScreenshot bool
Params map[string]string
}
type Client struct {
baseUrl string
authToken string
}
func New(baseUrl string, obtainAuthToken AuthTokenObtainer) (*Client, error) {
authToken, err := obtainAuthToken()
if err != nil {
return nil, err
}
return &Client{baseUrl, authToken}, nil
}
func (c *Client) Run(
ctx context.Context,
script string,
data interface{},
opts *Options,
) (*Output, error) {
if opts == nil {
opts = &Options{}
}
queryPars := url.Values{}
if opts.ErrorAutoScreenshot {
queryPars.Set("errorAutoScreenshot", "1")
}
for key, val := range opts.Params {
queryPars.Set(key, val)
}
output := &Output{}
if _, err := ezhttp.Post(
ctx,
c.baseUrl+"/job?"+queryPars.Encode(),
ezhttp.AuthBearer(c.authToken),
ezhttp.SendBody(strings.NewReader(script), "application/javascript"),
ezhttp.RespondsJson(output, false),
); err != nil {
return nil, fmt.Errorf("chromeserver: %w", err)
}
if output.Error != nil {
scriptError := *output.Error
// hack to not repeat error in JSON
output.Error = nil
responseJsonWithoutErrorRepeated, err := json.Marshal(output)
if err != nil {
return nil, err
}
return nil, fmt.Errorf(
"script error: %s\n\n%s",
scriptError,
responseJsonWithoutErrorRepeated)
}
if output.Data == nil {
return nil, errors.New("no data in response JSON")
}
return output, jsonfile.UnmarshalDisallowUnknownFields(bytes.NewReader(*output.Data), data)
}
func StaticToken(token string) AuthTokenObtainer {
return func() (string, error) {
return token, nil
}
}
func TokenFromEnv() (string, error) {
return osutil.GetenvRequired("CHROMESERVER_AUTH_TOKEN")
}