forked from cloudflare/cloudflare-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
workers.go
677 lines (602 loc) · 22 KB
/
workers.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
package cloudflare
import (
"bytes"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"math/rand"
"mime/multipart"
"net/http"
"net/textproto"
"time"
"github.com/pkg/errors"
)
// WorkerRequestParams provides parameters for worker requests for both enterprise and standard requests
type WorkerRequestParams struct {
ZoneID string
ScriptName string
}
// WorkerScriptParams provides a worker script and the associated bindings
type WorkerScriptParams struct {
Script string
// Bindings should be a map where the keys are the binding name, and the
// values are the binding content
Bindings map[string]WorkerBinding
}
// WorkerRoute is used to map traffic matching a URL pattern to a workers
//
// API reference: https://api.cloudflare.com/#worker-routes-properties
type WorkerRoute struct {
ID string `json:"id,omitempty"`
Pattern string `json:"pattern"`
Enabled bool `json:"enabled"` // this is deprecated: https://api.cloudflare.com/#worker-filters-deprecated--properties
Script string `json:"script,omitempty"`
}
// WorkerRoutesResponse embeds Response struct and slice of WorkerRoutes
type WorkerRoutesResponse struct {
Response
Routes []WorkerRoute `json:"result"`
}
// WorkerRouteResponse embeds Response struct and a single WorkerRoute
type WorkerRouteResponse struct {
Response
WorkerRoute `json:"result"`
}
// WorkerScript Cloudflare Worker struct with metadata
type WorkerScript struct {
WorkerMetaData
Script string `json:"script"`
}
// WorkerMetaData contains worker script information such as size, creation & modification dates
type WorkerMetaData struct {
ID string `json:"id,omitempty"`
ETAG string `json:"etag,omitempty"`
Size int `json:"size,omitempty"`
CreatedOn time.Time `json:"created_on,omitempty"`
ModifiedOn time.Time `json:"modified_on,omitempty"`
}
// WorkerListResponse wrapper struct for API response to worker script list API call
type WorkerListResponse struct {
Response
WorkerList []WorkerMetaData `json:"result"`
}
// WorkerScriptResponse wrapper struct for API response to worker script calls
type WorkerScriptResponse struct {
Response
WorkerScript `json:"result"`
}
// WorkerBindingType represents a particular type of binding
type WorkerBindingType string
func (b WorkerBindingType) String() string {
return string(b)
}
const (
// WorkerInheritBindingType is the type for inherited bindings
WorkerInheritBindingType WorkerBindingType = "inherit"
// WorkerKvNamespaceBindingType is the type for KV Namespace bindings
WorkerKvNamespaceBindingType WorkerBindingType = "kv_namespace"
// WorkerWebAssemblyBindingType is the type for Web Assembly module bindings
WorkerWebAssemblyBindingType WorkerBindingType = "wasm_module"
)
// WorkerBindingListItem a struct representing an individual binding in a list of bindings
type WorkerBindingListItem struct {
Name string `json:"name"`
Binding WorkerBinding
}
// WorkerBindingListResponse wrapper struct for API response to worker binding list API call
type WorkerBindingListResponse struct {
Response
BindingList []WorkerBindingListItem
}
// Workers supports multiple types of bindings, e.g. KV namespaces or WebAssembly modules, and each type
// of binding will be represented differently in the upload request body. At a high-level, every binding
// will specify metadata, which is a JSON object with the properties "name" and "type". Some types of bindings
// will also have additional metadata properties. For example, KV bindings also specify the KV namespace.
// In addition to the metadata, some binding types may need to include additional data as part of the
// multipart form. For example, WebAssembly bindings will include the contents of the WebAssembly module.
// WorkerBinding is the generic interface implemented by all of
// the various binding types
type WorkerBinding interface {
Type() WorkerBindingType
// serialize is responsible for returning the binding metadata as well as an optionally
// returning a function that can modify the multipart form body. For example, this is used
// by WebAssembly bindings to add a new part containing the WebAssembly module contents.
serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error)
}
// workerBindingMeta is the metadata portion of the binding
type workerBindingMeta = map[string]interface{}
// workerBindingBodyWriter allows for a binding to add additional parts to the multipart body
type workerBindingBodyWriter func(*multipart.Writer) error
// WorkerInheritBinding will just persist whatever binding content was previously uploaded
type WorkerInheritBinding struct {
// Optional parameter that allows for renaming a binding without changing
// its contents. If `OldName` is empty, the binding name will not be changed.
OldName string
}
// Type returns the type of the binding
func (b WorkerInheritBinding) Type() WorkerBindingType {
return WorkerInheritBindingType
}
func (b WorkerInheritBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
meta := workerBindingMeta{
"name": bindingName,
"type": b.Type(),
}
if b.OldName != "" {
meta["old_name"] = b.OldName
}
return meta, nil, nil
}
// WorkerKvNamespaceBinding is a binding to a Workers KV Namespace
//
// https://developers.cloudflare.com/workers/archive/api/resource-bindings/kv-namespaces/
type WorkerKvNamespaceBinding struct {
NamespaceID string
}
// Type returns the type of the binding
func (b WorkerKvNamespaceBinding) Type() WorkerBindingType {
return WorkerKvNamespaceBindingType
}
func (b WorkerKvNamespaceBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
if b.NamespaceID == "" {
return nil, nil, errors.Errorf(`NamespaceID for binding "%s" cannot be empty`, bindingName)
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"namespace_id": b.NamespaceID,
}, nil, nil
}
// WorkerWebAssemblyBinding is a binding to a WebAssembly module
//
// https://developers.cloudflare.com/workers/archive/api/resource-bindings/webassembly-modules/
type WorkerWebAssemblyBinding struct {
Module io.Reader
}
// Type returns the type of the binding
func (b WorkerWebAssemblyBinding) Type() WorkerBindingType {
return WorkerWebAssemblyBindingType
}
func (b WorkerWebAssemblyBinding) serialize(bindingName string) (workerBindingMeta, workerBindingBodyWriter, error) {
partName := getRandomPartName()
bodyWriter := func(mpw *multipart.Writer) error {
var hdr = textproto.MIMEHeader{}
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, partName))
hdr.Set("content-type", "application/wasm")
pw, err := mpw.CreatePart(hdr)
if err != nil {
return err
}
_, err = io.Copy(pw, b.Module)
return err
}
return workerBindingMeta{
"name": bindingName,
"type": b.Type(),
"part": partName,
}, bodyWriter, nil
}
// Each binding that adds a part to the multipart form body will need
// a unique part name so we just generate a random 128bit hex string
func getRandomPartName() string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return hex.EncodeToString(randBytes)
}
// DeleteWorker deletes worker for a zone.
//
// API reference: https://api.cloudflare.com/#worker-script-delete-worker
func (api *API) DeleteWorker(requestParams *WorkerRequestParams) (WorkerScriptResponse, error) {
// if ScriptName is provided we will treat as org request
if requestParams.ScriptName != "" {
return api.deleteWorkerWithName(requestParams.ScriptName)
}
uri := "/zones/" + requestParams.ZoneID + "/workers/script"
res, err := api.makeRequest("DELETE", uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
// DeleteWorkerWithName deletes worker for a zone.
// This is an enterprise only feature https://developers.cloudflare.com/workers/api/config-api-for-enterprise
// account must be specified as api option https://godoc.org/github.com/cloudflare/cloudflare-go#UsingAccount
//
// API reference: https://api.cloudflare.com/#worker-script-delete-worker
func (api *API) deleteWorkerWithName(scriptName string) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required for enterprise only request")
}
uri := "/accounts/" + api.AccountID + "/workers/scripts/" + scriptName
res, err := api.makeRequest("DELETE", uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
// DownloadWorker fetch raw script content for your worker returns []byte containing worker code js
//
// API reference: https://api.cloudflare.com/#worker-script-download-worker
func (api *API) DownloadWorker(requestParams *WorkerRequestParams) (WorkerScriptResponse, error) {
if requestParams.ScriptName != "" {
return api.downloadWorkerWithName(requestParams.ScriptName)
}
uri := "/zones/" + requestParams.ZoneID + "/workers/script"
res, err := api.makeRequest("GET", uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
r.Script = string(res)
r.Success = true
return r, nil
}
// DownloadWorkerWithName fetch raw script content for your worker returns string containing worker code js
// This is an enterprise only feature https://developers.cloudflare.com/workers/api/config-api-for-enterprise/
//
// API reference: https://api.cloudflare.com/#worker-script-download-worker
func (api *API) downloadWorkerWithName(scriptName string) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required for enterprise only request")
}
uri := "/accounts/" + api.AccountID + "/workers/scripts/" + scriptName
res, err := api.makeRequest("GET", uri, nil)
var r WorkerScriptResponse
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
r.Script = string(res)
r.Success = true
return r, nil
}
// ListWorkerBindings returns all the bindings for a particular worker
func (api *API) ListWorkerBindings(requestParams *WorkerRequestParams) (WorkerBindingListResponse, error) {
if requestParams.ScriptName == "" {
return WorkerBindingListResponse{}, errors.New("ScriptName is required")
}
if api.AccountID == "" {
return WorkerBindingListResponse{}, errors.New("account ID required")
}
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings", api.AccountID, requestParams.ScriptName)
var jsonRes struct {
Response
Bindings []workerBindingMeta `json:"result"`
}
var r WorkerBindingListResponse
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &jsonRes)
if err != nil {
return r, errors.Wrap(err, errUnmarshalError)
}
r = WorkerBindingListResponse{
Response: jsonRes.Response,
BindingList: make([]WorkerBindingListItem, 0, len(jsonRes.Bindings)),
}
for _, jsonBinding := range jsonRes.Bindings {
name, ok := jsonBinding["name"].(string)
if !ok {
return r, errors.Errorf("Binding missing name %v", jsonBinding)
}
bType, ok := jsonBinding["type"].(string)
if !ok {
return r, errors.Errorf("Binding missing type %v", jsonBinding)
}
bindingListItem := WorkerBindingListItem{
Name: name,
}
switch WorkerBindingType(bType) {
case WorkerKvNamespaceBindingType:
namespaceID := jsonBinding["namespace_id"].(string)
bindingListItem.Binding = WorkerKvNamespaceBinding{
NamespaceID: namespaceID,
}
case WorkerWebAssemblyBindingType:
bindingListItem.Binding = WorkerWebAssemblyBinding{
Module: &bindingContentReader{
api: api,
requestParams: requestParams,
bindingName: name,
},
}
default:
bindingListItem.Binding = WorkerInheritBinding{}
}
r.BindingList = append(r.BindingList, bindingListItem)
}
return r, nil
}
// bindingContentReader is an io.Reader that will lazily load the
// raw bytes for a binding from the API when the Read() method
// is first called. This is only useful for binding types
// that store raw bytes, like WebAssembly modules
type bindingContentReader struct {
api *API
requestParams *WorkerRequestParams
bindingName string
content []byte
position int
}
func (b *bindingContentReader) Read(p []byte) (n int, err error) {
// Lazily load the content when Read() is first called
if b.content == nil {
uri := fmt.Sprintf("/accounts/%s/workers/scripts/%s/bindings/%s/content", b.api.AccountID, b.requestParams.ScriptName, b.bindingName)
res, err := b.api.makeRequest("GET", uri, nil)
if err != nil {
return 0, errors.Wrap(err, errMakeRequestError)
}
b.content = res
}
if b.position >= len(b.content) {
return 0, io.EOF
}
bytesRemaining := len(b.content) - b.position
bytesToProcess := 0
if len(p) < bytesRemaining {
bytesToProcess = len(p)
} else {
bytesToProcess = bytesRemaining
}
for i := 0; i < bytesToProcess; i++ {
p[i] = b.content[b.position]
b.position = b.position + 1
}
return bytesToProcess, nil
}
// ListWorkerScripts returns list of worker scripts for given account.
//
// This is an enterprise only feature https://developers.cloudflare.com/workers/api/config-api-for-enterprise
//
// API reference: https://developers.cloudflare.com/workers/api/config-api-for-enterprise/
func (api *API) ListWorkerScripts() (WorkerListResponse, error) {
if api.AccountID == "" {
return WorkerListResponse{}, errors.New("account ID required for enterprise only request")
}
uri := "/accounts/" + api.AccountID + "/workers/scripts"
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return WorkerListResponse{}, errors.Wrap(err, errMakeRequestError)
}
var r WorkerListResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerListResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
// UploadWorker push raw script content for your worker.
//
// API reference: https://api.cloudflare.com/#worker-script-upload-worker
func (api *API) UploadWorker(requestParams *WorkerRequestParams, data string) (WorkerScriptResponse, error) {
if requestParams.ScriptName != "" {
return api.uploadWorkerWithName(requestParams.ScriptName, "application/javascript", []byte(data))
}
return api.uploadWorkerForZone(requestParams.ZoneID, "application/javascript", []byte(data))
}
// UploadWorkerWithBindings push raw script content and bindings for your worker
//
// API reference: https://api.cloudflare.com/#worker-script-upload-worker
func (api *API) UploadWorkerWithBindings(requestParams *WorkerRequestParams, data *WorkerScriptParams) (WorkerScriptResponse, error) {
contentType, body, err := formatMultipartBody(data)
if err != nil {
return WorkerScriptResponse{}, err
}
if requestParams.ScriptName != "" {
return api.uploadWorkerWithName(requestParams.ScriptName, contentType, body)
}
return api.uploadWorkerForZone(requestParams.ZoneID, contentType, body)
}
func (api *API) uploadWorkerForZone(zoneID, contentType string, body []byte) (WorkerScriptResponse, error) {
uri := "/zones/" + zoneID + "/workers/script"
headers := make(http.Header)
headers.Set("Content-Type", contentType)
res, err := api.makeRequestWithHeaders("PUT", uri, body, headers)
var r WorkerScriptResponse
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
func (api *API) uploadWorkerWithName(scriptName, contentType string, body []byte) (WorkerScriptResponse, error) {
if api.AccountID == "" {
return WorkerScriptResponse{}, errors.New("account ID required for enterprise only request")
}
uri := "/accounts/" + api.AccountID + "/workers/scripts/" + scriptName
headers := make(http.Header)
headers.Set("Content-Type", contentType)
res, err := api.makeRequestWithHeaders("PUT", uri, body, headers)
var r WorkerScriptResponse
if err != nil {
return r, errors.Wrap(err, errMakeRequestError)
}
err = json.Unmarshal(res, &r)
if err != nil {
return r, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
// Returns content-type, body, error
func formatMultipartBody(params *WorkerScriptParams) (string, []byte, error) {
var buf = &bytes.Buffer{}
var mpw = multipart.NewWriter(buf)
defer mpw.Close()
// Write metadata part
scriptPartName := "script"
meta := struct {
BodyPart string `json:"body_part"`
Bindings []workerBindingMeta `json:"bindings"`
}{
BodyPart: scriptPartName,
Bindings: make([]workerBindingMeta, 0, len(params.Bindings)),
}
bodyWriters := make([]workerBindingBodyWriter, 0, len(params.Bindings))
for name, b := range params.Bindings {
bindingMeta, bodyWriter, err := b.serialize(name)
if err != nil {
return "", nil, err
}
meta.Bindings = append(meta.Bindings, bindingMeta)
bodyWriters = append(bodyWriters, bodyWriter)
}
var hdr = textproto.MIMEHeader{}
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, "metadata"))
hdr.Set("content-type", "application/json")
pw, err := mpw.CreatePart(hdr)
if err != nil {
return "", nil, err
}
metaJSON, err := json.Marshal(meta)
if err != nil {
return "", nil, err
}
_, err = pw.Write(metaJSON)
if err != nil {
return "", nil, err
}
// Write script part
hdr = textproto.MIMEHeader{}
hdr.Set("content-disposition", fmt.Sprintf(`form-data; name="%s"`, scriptPartName))
hdr.Set("content-type", "application/javascript")
pw, err = mpw.CreatePart(hdr)
if err != nil {
return "", nil, err
}
_, err = pw.Write([]byte(params.Script))
if err != nil {
return "", nil, err
}
// Write other bindings with parts
for _, w := range bodyWriters {
if w != nil {
err = w(mpw)
if err != nil {
return "", nil, err
}
}
}
mpw.Close()
return mpw.FormDataContentType(), buf.Bytes(), nil
}
// CreateWorkerRoute creates worker route for a zone
//
// API reference: https://api.cloudflare.com/#worker-filters-create-filter, https://api.cloudflare.com/#worker-routes-create-route
func (api *API) CreateWorkerRoute(zoneID string, route WorkerRoute) (WorkerRouteResponse, error) {
pathComponent, err := getRouteEndpoint(api, route)
if err != nil {
return WorkerRouteResponse{}, err
}
uri := "/zones/" + zoneID + "/workers/" + pathComponent
res, err := api.makeRequest("POST", uri, route)
if err != nil {
return WorkerRouteResponse{}, errors.Wrap(err, errMakeRequestError)
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
// DeleteWorkerRoute deletes worker route for a zone
//
// API reference: https://api.cloudflare.com/#worker-routes-delete-route
func (api *API) DeleteWorkerRoute(zoneID string, routeID string) (WorkerRouteResponse, error) {
uri := "/zones/" + zoneID + "/workers/routes/" + routeID
res, err := api.makeRequest("DELETE", uri, nil)
if err != nil {
return WorkerRouteResponse{}, errors.Wrap(err, errMakeRequestError)
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
// ListWorkerRoutes returns list of worker routes
//
// API reference: https://api.cloudflare.com/#worker-filters-list-filters, https://api.cloudflare.com/#worker-routes-list-routes
func (api *API) ListWorkerRoutes(zoneID string) (WorkerRoutesResponse, error) {
pathComponent := "filters"
// Unfortunately we don't have a good signal of whether the user is wanting
// to use the deprecated filters endpoint (https://api.cloudflare.com/#worker-filters-list-filters)
// or the multi-script routes endpoint (https://api.cloudflare.com/#worker-script-list-workers)
//
// The filters endpoint does not support API tokens, so if an API token is specified we need to use
// the routes endpoint. Otherwise, since the multi-script API endpoints that operate on a script
// require an AccountID, we assume that anyone specifying an AccountID is using the routes endpoint.
// This is likely too presumptuous. In the next major version, we should just remove the deprecated
// filter endpoints entirely to avoid this ambiguity.
if api.AccountID != "" || api.APIToken != "" {
pathComponent = "routes"
}
uri := "/zones/" + zoneID + "/workers/" + pathComponent
res, err := api.makeRequest("GET", uri, nil)
if err != nil {
return WorkerRoutesResponse{}, errors.Wrap(err, errMakeRequestError)
}
var r WorkerRoutesResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRoutesResponse{}, errors.Wrap(err, errUnmarshalError)
}
for i := range r.Routes {
route := &r.Routes[i]
// The Enabled flag will not be set in the multi-script API response
// so we manually set it to true if the script name is not empty
// in case any multi-script customers rely on the Enabled field
if route.Script != "" {
route.Enabled = true
}
}
return r, nil
}
// UpdateWorkerRoute updates worker route for a zone.
//
// API reference: https://api.cloudflare.com/#worker-filters-update-filter, https://api.cloudflare.com/#worker-routes-update-route
func (api *API) UpdateWorkerRoute(zoneID string, routeID string, route WorkerRoute) (WorkerRouteResponse, error) {
pathComponent, err := getRouteEndpoint(api, route)
if err != nil {
return WorkerRouteResponse{}, err
}
uri := "/zones/" + zoneID + "/workers/" + pathComponent + "/" + routeID
res, err := api.makeRequest("PUT", uri, route)
if err != nil {
return WorkerRouteResponse{}, errors.Wrap(err, errMakeRequestError)
}
var r WorkerRouteResponse
err = json.Unmarshal(res, &r)
if err != nil {
return WorkerRouteResponse{}, errors.Wrap(err, errUnmarshalError)
}
return r, nil
}
func getRouteEndpoint(api *API, route WorkerRoute) (string, error) {
if route.Script != "" && route.Enabled == true {
return "", errors.New("Only `Script` or `Enabled` may be specified for a WorkerRoute, not both")
}
// For backwards-compatability, fallback to the deprecated filter
// endpoint if Enabled == true
// https://api.cloudflare.com/#worker-filters-deprecated--properties
if route.Enabled == true {
return "filters", nil
}
return "routes", nil
}