-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoverage.html
More file actions
1808 lines (1569 loc) · 68.7 KB
/
coverage.html
File metadata and controls
1808 lines (1569 loc) · 68.7 KB
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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>rest: Go Coverage Report</title>
<style>
body {
background: black;
color: rgb(80, 80, 80);
}
body, pre, #legend span {
font-family: Menlo, monospace;
font-weight: bold;
}
#topbar {
background: black;
position: fixed;
top: 0; left: 0; right: 0;
height: 42px;
border-bottom: 1px solid rgb(80, 80, 80);
}
#content {
margin-top: 50px;
}
#nav, #legend {
float: left;
margin-left: 10px;
}
#legend {
margin-top: 12px;
}
#nav {
margin-top: 10px;
}
#legend span {
margin: 0 5px;
}
.cov0 { color: rgb(192, 0, 0) }
.cov1 { color: rgb(128, 128, 128) }
.cov2 { color: rgb(116, 140, 131) }
.cov3 { color: rgb(104, 152, 134) }
.cov4 { color: rgb(92, 164, 137) }
.cov5 { color: rgb(80, 176, 140) }
.cov6 { color: rgb(68, 188, 143) }
.cov7 { color: rgb(56, 200, 146) }
.cov8 { color: rgb(44, 212, 149) }
.cov9 { color: rgb(32, 224, 152) }
.cov10 { color: rgb(20, 236, 155) }
</style>
</head>
<body>
<div id="topbar">
<div id="nav">
<select id="files">
<option value="file0">github.com/KarpelesLab/rest/error.go (44.4%)</option>
<option value="file1">github.com/KarpelesLab/rest/nwg.go (100.0%)</option>
<option value="file2">github.com/KarpelesLab/rest/proxy.go (0.0%)</option>
<option value="file3">github.com/KarpelesLab/rest/response.go (31.0%)</option>
<option value="file4">github.com/KarpelesLab/rest/rest.go (53.3%)</option>
<option value="file5">github.com/KarpelesLab/rest/router.go (0.0%)</option>
<option value="file6">github.com/KarpelesLab/rest/sender.go (0.0%)</option>
<option value="file7">github.com/KarpelesLab/rest/spot.go (0.0%)</option>
<option value="file8">github.com/KarpelesLab/rest/time.go (0.0%)</option>
<option value="file9">github.com/KarpelesLab/rest/token.go (0.0%)</option>
<option value="file10">github.com/KarpelesLab/rest/upload.go (56.5%)</option>
</select>
</div>
<div id="legend">
<span>not tracked</span>
<span class="cov0">not covered</span>
<span class="cov8">covered</span>
</div>
</div>
<div id="content">
<pre class="file" id="file0" style="display: none">// Package rest provides a client for interacting with RESTful API services.
package rest
import (
"errors"
"fmt"
"io/fs"
"os"
)
// ErrLoginRequired is returned when an API endpoint requires authentication
// but no valid token was provided.
var ErrLoginRequired = errors.New("login required")
// Error represents an error returned by a REST API endpoint.
// It wraps the Response object and provides standard error interfaces.
type Error struct {
Response *Response
parent error
}
// Error returns a string representation of the REST API error.
func (r *Error) Error() string <span class="cov0" title="0">{
return fmt.Sprintf("[rest] error from server: %s", r.Response.Error)
}</span>
// Unwrap implements the errors.Unwrapper interface to allow error checking with errors.Is.
// It maps REST API errors to standard Go errors where applicable (e.g., 403 to os.ErrPermission).
func (r *Error) Unwrap() error <span class="cov8" title="1">{
if r.parent != nil </span><span class="cov0" title="0">{
return r.parent
}</span>
// check for various type of errors
<span class="cov8" title="1">switch r.Response.Code </span>{
case 403:<span class="cov8" title="1">
return os.ErrPermission</span>
case 404:<span class="cov8" title="1">
return fs.ErrNotExist</span>
default:<span class="cov0" title="0">
return nil</span>
}
}
// HttpError represents an HTTP transport error that occurred during a REST API request.
// It captures HTTP status codes and response bodies for debugging.
type HttpError struct {
Code int
Body []byte
e error // unwrap error
}
// Error returns a string representation of the HTTP error.
func (e *HttpError) Error() string <span class="cov0" title="0">{
return fmt.Sprintf("HTTP Error %d: %s", e.Code, e.Body)
}</span>
// Unwrap implements the errors.Unwrapper interface to allow error checking with errors.Is.
// It returns the underlying error, if any.
func (e *HttpError) Unwrap() error <span class="cov0" title="0">{
return e.e
}</span>
</pre>
<pre class="file" id="file1" style="display: none">package rest
import "sync"
type numeralWaitGroup struct {
cnt int
cd *sync.Cond
lk sync.RWMutex
}
func newNWG() *numeralWaitGroup <span class="cov8" title="1">{
res := &numeralWaitGroup{}
res.cd = sync.NewCond(res.lk.RLocker())
return res
}</span>
func (n *numeralWaitGroup) Add(delta int) <span class="cov8" title="1">{
n.lk.Lock()
defer n.lk.Unlock()
n.cnt += delta
if delta < 0 </span><span class="cov8" title="1">{
n.cd.Broadcast()
}</span>
}
func (n *numeralWaitGroup) Done() <span class="cov8" title="1">{
n.Add(-1)
}</span>
// Wait waits until there is less or equal than "min" tasks
func (n *numeralWaitGroup) Wait(min int) <span class="cov8" title="1">{
n.lk.RLock()
defer n.lk.RUnlock()
for </span><span class="cov8" title="1">{
if n.cnt <= min </span><span class="cov8" title="1">{
return
}</span>
<span class="cov8" title="1">n.cd.Wait()</span>
}
}
</pre>
<pre class="file" id="file2" style="display: none">//go:build !wasm
package rest
import (
"net/http"
"net/http/httputil"
"net/url"
)
var (
SystemProxy = &httputil.ReverseProxy{
Director: systemProxyDirector,
Transport: RestHttpClient.Transport,
}
)
func systemProxyDirector(req *http.Request) <span class="cov0" title="0">{
if bk, ok := req.Context().Value(BackendURL).(*url.URL); ok && bk != nil </span><span class="cov0" title="0">{
req.URL.Scheme = bk.Scheme
req.URL.Host = bk.Host
}</span> else<span class="cov0" title="0"> {
req.URL.Scheme = Scheme
req.URL.Host = Host
}</span>
//req.Host = Host
<span class="cov0" title="0">req.Header.Set("Host", req.URL.Host)
req.Header.Set("Sec-Rest-Http", "true")
req.Header.Del("Accept-Encoding")
if _, ok := req.Header["User-Agent"]; !ok </span><span class="cov0" title="0">{
// explicitly disable User-Agent so it's not set to default value
req.Header.Set("User-Agent", "")
}</span>
<span class="cov0" title="0">if _, ok := req.Header["Cookie"]; ok </span><span class="cov0" title="0">{
req.Header.Del("Cookie")
}</span>
// let context alter request as needed
<span class="cov0" title="0">req.Context().Value(req)</span>
}
</pre>
<pre class="file" id="file3" style="display: none">package rest
import (
"context"
"fmt"
"strings"
"sync"
"github.com/KarpelesLab/pjson"
"github.com/KarpelesLab/typutil"
)
// Param is a convenience type for parameters passed to REST API requests.
type Param map[string]any
// Response represents a REST API response with standard fields.
// It handles different result types and provides methods to access response data.
type Response struct {
Result string `json:"result"` // "success" or "error" (or "redirect")
Data pjson.RawMessage `json:"data,omitempty"`
Error string `json:"error,omitempty"`
Code int `json:"code,omitempty"` // for errors
Extra string `json:"extra,omitempty"`
Token string `json:"token,omitempty"`
Paging any `json:"paging,omitempty"`
Job any `json:"job,omitempty"`
Time any `json:"time,omitempty"`
Access any `json:"access,omitempty"`
Exception string `json:"exception,omitempty"`
RedirectUrl string `json:"redirect_url,omitempty"`
RedirectCode int `json:"redirect_code,omitempty"`
dataParsed any
dataError error
dataParse sync.Once
}
// ReadValue returns the parsed data from the response.
// It's an alias for Value() that satisfies interfaces requiring a context parameter.
func (r *Response) ReadValue(ctx context.Context) (any, error) <span class="cov0" title="0">{
return r.Value()
}</span>
// OffsetGet implements the typutil.Getter interface for Response objects.
// It allows accessing response fields by key, with special handling for metadata keys
// prefixed with '@' (e.g., @error, @code).
func (r *Response) OffsetGet(ctx context.Context, key string) (any, error) <span class="cov0" title="0">{
if strings.HasPrefix(key, "@") </span><span class="cov0" title="0">{
switch key[1:] </span>{
case "error":<span class="cov0" title="0">
return r.Error, nil</span>
case "code":<span class="cov0" title="0">
return r.Code, nil</span>
case "extra":<span class="cov0" title="0">
return r.Extra, nil</span>
case "token":<span class="cov0" title="0">
return r.Token, nil</span>
case "paging":<span class="cov0" title="0">
return r.Paging, nil</span>
case "job":<span class="cov0" title="0">
return r.Job, nil</span>
case "time":<span class="cov0" title="0">
return r.Time, nil</span>
case "access":<span class="cov0" title="0">
return r.Access, nil</span>
case "exception":<span class="cov0" title="0">
return r.Exception, nil</span>
}
}
// return value
<span class="cov0" title="0">return r.Get(key)</span>
}
// Raw returns the parsed data from the response.
// It's implemented as r.Value() for compatibility with older code.
func (r *Response) Raw() (any, error) <span class="cov0" title="0">{
return r.Value()
}</span>
// FullRaw returns the complete response as a map, including both the data payload
// and all metadata fields (result, error, code, etc.).
func (r *Response) FullRaw() (map[string]any, error) <span class="cov0" title="0">{
data, err := r.Value()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">resp := map[string]any{"result": r.Result, "data": data}
if r.Error != "" </span><span class="cov0" title="0">{
resp["error"] = r.Error
}</span>
<span class="cov0" title="0">if r.Code != 0 </span><span class="cov0" title="0">{
resp["code"] = r.Code
}</span>
<span class="cov0" title="0">if r.Extra != "" </span><span class="cov0" title="0">{
resp["extra"] = r.Extra
}</span>
<span class="cov0" title="0">if r.Token != "" </span><span class="cov0" title="0">{
resp["token"] = r.Token
}</span>
<span class="cov0" title="0">if r.Paging != nil </span><span class="cov0" title="0">{
resp["paging"] = r.Paging
}</span>
<span class="cov0" title="0">if r.Job != nil </span><span class="cov0" title="0">{
resp["job"] = r.Job
}</span>
<span class="cov0" title="0">if r.Time != nil </span><span class="cov0" title="0">{
resp["time"] = r.Time
}</span>
<span class="cov0" title="0">if r.Access != nil </span><span class="cov0" title="0">{
resp["access"] = r.Access
}</span>
<span class="cov0" title="0">if r.Exception != "" </span><span class="cov0" title="0">{
resp["exception"] = r.Exception
}</span>
<span class="cov0" title="0">if r.RedirectUrl != "" </span><span class="cov0" title="0">{
resp["redirect_url"] = r.RedirectUrl
}</span>
<span class="cov0" title="0">if r.RedirectCode != 0 </span><span class="cov0" title="0">{
resp["redirect_code"] = r.RedirectCode
}</span>
<span class="cov0" title="0">return resp, nil</span>
}
// Apply unmarshals the response data into the provided value.
//
// Parameters:
//
// - v: The target object to unmarshal into
//
// Returns: an error if unmarshaling fails
func (r *Response) Apply(v any) error <span class="cov8" title="1">{
return pjson.Unmarshal(r.Data, v)
}</span>
// ResponseAs is a generic helper that unmarshals a response into type T.
//
// Parameters:
//
// - r: The Response object containing data to unmarshal
//
// Returns: the unmarshaled object of type T and any error encountered
func ResponseAs[T any](r *Response) (T, error) <span class="cov8" title="1">{
var target T
err := r.Apply(&target)
return target, err
}</span>
// ApplyContext unmarshals the response data into the provided value using a context.
//
// Parameters:
//
// - ctx: Context for unmarshaling
// - v: The target object to unmarshal into
//
// Returns: an error if unmarshaling fails
func (r *Response) ApplyContext(ctx context.Context, v any) error <span class="cov0" title="0">{
return pjson.UnmarshalContext(ctx, r.Data, v)
}</span>
// Value returns the parsed data from the response.
// It lazily parses the JSON data on first access and caches the result.
//
// Returns: the parsed data and any error encountered during parsing
func (r *Response) Value() (any, error) <span class="cov8" title="1">{
r.dataParse.Do(r.ParseData)
return r.dataParsed, r.dataError
}</span>
// ValueContext returns the parsed data from the response, similar to Value().
// It's provided for interface compatibility with methods requiring a context.
//
// Parameters:
//
// - ctx: Context (not used internally but provided for interface compatibility)
//
// Returns: the parsed data and any error encountered during parsing
func (r *Response) ValueContext(ctx context.Context) (any, error) <span class="cov0" title="0">{
r.dataParse.Do(r.ParseData)
return r.dataParsed, r.dataError
}</span>
// ParseData parses the JSON data in the response.
// This is called automatically by Value() and ValueContext() methods.
func (r *Response) ParseData() <span class="cov8" title="1">{
r.dataError = pjson.Unmarshal(r.Data, &r.dataParsed)
}</span>
// Get retrieves a value from the response data by a slash-separated path.
// For example, "user/name" would access the "name" field inside the "user" object.
//
// Parameters:
//
// - v: Slash-separated path to the requested value
//
// Returns: the value at the specified path and any error encountered
func (r *Response) Get(v string) (any, error) <span class="cov8" title="1">{
va := strings.Split(v, "/")
cur, err := r.Value()
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">for _, sub := range va </span><span class="cov8" title="1">{
if sub == "" </span><span class="cov8" title="1">{
continue</span>
}
// we assume each sub will be an index in cur as a map
<span class="cov8" title="1">cur, err = typutil.OffsetGet(context.Background(), cur, sub)
if err != nil </span><span class="cov0" title="0">{
return cur, err
}</span>
<span class="cov8" title="1">if cur == nil </span><span class="cov0" title="0">{
return nil, nil
}</span>
}
<span class="cov8" title="1">return cur, nil</span>
}
// GetString retrieves a string value from the response data by a slash-separated path.
// This is a convenience method that calls Get() and converts the result to a string.
//
// Parameters:
//
// - v: Slash-separated path to the requested string value
//
// Returns: the string value at the specified path and any error encountered
func (r *Response) GetString(v string) (string, error) <span class="cov8" title="1">{
res, err := r.Get(v)
if err != nil </span><span class="cov0" title="0">{
return "", err
}</span>
<span class="cov8" title="1">str, ok := res.(string)
if !ok </span><span class="cov0" title="0">{
return fmt.Sprintf("%v", str), fmt.Errorf("unexpected type %T for string %s", res, v)
}</span>
<span class="cov8" title="1">return str, nil</span>
}
</pre>
<pre class="file" id="file4" style="display: none">// Package rest provides a client for interacting with RESTful API services.
// It simplifies making HTTP requests to REST endpoints, handling authentication,
// token renewal, and response parsing.
package rest
import (
"bytes"
"context"
"fmt"
"io"
"io/ioutil"
"log/slog"
"net/http"
"net/url"
"time"
"github.com/KarpelesLab/pjson"
"github.com/KarpelesLab/webutil"
)
var (
// Debug enables verbose logging of REST API requests and responses
Debug = false
// Scheme defines the URL scheme for API requests (http or https)
Scheme = "https"
// Host defines the default hostname for API requests
Host = "www.atonline.com"
)
// Apply makes a REST API request and unmarshals the response data into the target object.
// It handles authentication, error parsing, and JSON unmarshaling.
//
// Parameters:
//
// - ctx: Context for the request, may contain authentication tokens
// - path: API endpoint path
// - method: HTTP method (GET, POST, PUT, etc.)
// - param: Request parameters or body content
// - target: Destination object for unmarshaled response data
//
// Returns: an error if the request fails or response cannot be unmarshaled.
func Apply(ctx context.Context, path, method string, param any, target any) error <span class="cov8" title="1">{
res, err := Do(ctx, path, method, param)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov8" title="1">err = pjson.UnmarshalContext(ctx, res.Data, target)
if Debug && err != nil </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, res.Data), "event", "rest:not_json")
}</span>
<span class="cov8" title="1">return err</span>
}
// As makes a REST API request and returns the response data unmarshaled into the specified type T.
// This is a generic version of Apply that returns the target object directly.
//
// Parameters:
//
// - ctx: Context for the request, may contain authentication tokens
// - path: API endpoint path
// - method: HTTP method (GET, POST, PUT, etc.)
// - param: Request parameters or body content
//
// Returns: the unmarshaled object of type T and any error encountered.
func As[T any](ctx context.Context, path, method string, param any) (T, error) <span class="cov8" title="1">{
var target T
res, err := Do(ctx, path, method, param)
if err != nil </span><span class="cov0" title="0">{
return target, err
}</span>
<span class="cov8" title="1">err = pjson.UnmarshalContext(ctx, res.Data, &target)
if Debug && err != nil </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, res.Data), "event", "rest:not_json")
}</span>
<span class="cov8" title="1">return target, err</span>
}
// Do executes a REST API request and returns the raw Response object.
// It handles token authentication, token renewal, parameter encoding, and error parsing.
//
// Parameters:
//
// - ctx: Context for the request, may contain authentication tokens
// - path: API endpoint path
// - method: HTTP method (GET, POST, PUT, etc.)
// - param: Request parameters or body content
//
// Returns: the raw Response object and any error encountered during the request.
func Do(ctx context.Context, path, method string, param any) (*Response, error) <span class="cov8" title="1">{
var backend *url.URL
if bk, ok := ctx.Value(BackendURL).(*url.URL); ok && bk != nil </span><span class="cov0" title="0">{
backend = bk
}</span> else<span class="cov8" title="1"> {
backend = &url.URL{Scheme: Scheme, Host: Host}
}</span>
// build http request
<span class="cov8" title="1">r := &http.Request{
Method: method,
URL: &url.URL{
Scheme: backend.Scheme,
Host: backend.Host,
Path: "/_special/rest/" + path,
},
Header: make(http.Header),
}
r.Header.Set("Sec-Rest-Http", "false")
// add parameters (depending on method)
switch method </span>{
case "GET", "HEAD", "OPTIONS":<span class="cov8" title="1">
// need to pass parameters in GET
data, err := pjson.MarshalContext(ctx, param)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">r.URL.RawQuery = "_=" + url.QueryEscape(string(data))</span>
case "PUT", "POST", "PATCH":<span class="cov8" title="1">
data, err := pjson.MarshalContext(ctx, param)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">buf := bytes.NewReader(data)
r.Body = ioutil.NopCloser(buf)
r.ContentLength = int64(len(data))
r.GetBody = func() (io.ReadCloser, error) </span><span class="cov0" title="0">{
reader := bytes.NewReader(data)
return ioutil.NopCloser(reader), nil
}</span>
<span class="cov8" title="1">r.Header.Set("Content-Type", "application/json")</span>
case "DELETE":<span class="cov0" title="0"></span>
// nothing
default:<span class="cov0" title="0">
return nil, fmt.Errorf("invalid request method %s", method)</span>
}
// final configuration
<span class="cov8" title="1">ctx.Value(r)
// check for rest token
var token *Token
if t, ok := ctx.Value(tokenValue(0)).(*Token); t != nil && ok </span><span class="cov0" title="0">{
// set token & authorization header
token = t
r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
}</span>
<span class="cov8" title="1">t := time.Now()
resp, err := RestHttpClient.Do(r)
if err != nil </span><span class="cov0" title="0">{
return nil, fmt.Errorf("failed to run rest query: %w", err)
}</span>
<span class="cov8" title="1">defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
//log.Printf(ctx, "[rest] Response to %s %s: %s", method, path, body)
<span class="cov8" title="1">result := &Response{}
err = pjson.UnmarshalContext(ctx, body, result)
if err != nil </span><span class="cov0" title="0">{
if Debug </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, body), "event", "rest:not_json")
}</span>
<span class="cov0" title="0">if resp.StatusCode >= 400 </span><span class="cov0" title="0">{
// this is an error response
err = &HttpError{Code: resp.StatusCode, Body: body, e: err}
}</span>
<span class="cov0" title="0">return nil, err</span>
}
<span class="cov8" title="1">if token != nil && result.Token == "invalid_request_token" && result.Extra == "token_expired" </span><span class="cov0" title="0">{
// token has expired, renew token & re-run process
if Debug </span><span class="cov0" title="0">{
slog.DebugContext(ctx, "Token has expired, requesting renew", "event", "rest:token_renew")
}</span>
<span class="cov0" title="0">if err := token.renew(ctx); err != nil </span><span class="cov0" title="0">{
// error
if Debug </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to renew token: %s", err), "event", "rest:token_renew_fail")
}</span>
<span class="cov0" title="0">return nil, err</span>
}
// re-run query
<span class="cov0" title="0">r.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token.AccessToken))
resp, err := RestHttpClient.Do(r)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">err = pjson.UnmarshalContext(ctx, body, result)
if err != nil </span><span class="cov0" title="0">{
if Debug </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, body), "event", "rest:not_json")
}</span>
<span class="cov0" title="0">return nil, err</span>
}
}
<span class="cov8" title="1">if Debug </span><span class="cov0" title="0">{
if v, ok := ctx.Value(SkipDebugLog).(bool); !ok || !v </span><span class="cov0" title="0">{
d := time.Since(t)
slog.DebugContext(ctx, fmt.Sprintf("[rest] %s %s => %s", method, path, d), "event", "rest:debug_query", "rest:method", method, "rest:request", path, "rest:duration", d)
}</span>
}
<span class="cov8" title="1">if result.Result == "redirect" </span><span class="cov8" title="1">{
if result.Exception == "Exception\\Login" </span><span class="cov0" title="0">{
return nil, ErrLoginRequired
}</span>
<span class="cov8" title="1">url, err := url.Parse(result.RedirectUrl)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov8" title="1">return nil, webutil.RedirectErrorCode(url, result.RedirectCode)</span>
}
<span class="cov8" title="1">if result.Result == "error" </span><span class="cov8" title="1">{
return nil, &Error{Response: result}
}</span>
<span class="cov8" title="1">return result, nil</span>
}
</pre>
<pre class="file" id="file5" style="display: none">//go:build !wasm
package rest
import "net/http"
type RouterType struct {
}
var Router *RouterType = &RouterType{}
func (h *RouterType) ServeHTTP(w http.ResponseWriter, req *http.Request) <span class="cov0" title="0">{
// fallback to PHP, add prefix for rest
req.URL.Path = "/_special/rest" + req.URL.Path
SystemProxy.ServeHTTP(w, req)
}</span>
</pre>
<pre class="file" id="file6" style="display: none">package rest
import (
"context"
"io"
)
type SenderInterface interface {
Send(from string, to []string, msg io.WriterTo) error
}
type TokenSender struct {
Token string
}
type restSender struct{}
var Sender SenderInterface = restSender{}
func (s restSender) Send(from string, to []string, msg io.WriterTo) error <span class="cov0" title="0">{
reader, writer := io.Pipe()
defer reader.Close()
go func() </span><span class="cov0" title="0">{
defer writer.Close()
msg.WriteTo(writer)
}</span>()
<span class="cov0" title="0">_, err := Upload(context.Background(), "MTA:send", "POST", map[string]any{"from": from, "to": to}, reader, "message/rfc822")
return err</span>
}
func (s *TokenSender) Send(from string, to []string, msg io.WriterTo) error <span class="cov0" title="0">{
reader, writer := io.Pipe()
defer reader.Close()
go func() </span><span class="cov0" title="0">{
defer writer.Close()
msg.WriteTo(writer)
}</span>()
<span class="cov0" title="0">_, err := Upload(context.Background(), "MTA:send", "POST", map[string]any{"from": from, "to": to, "token": s.Token}, reader, "message/rfc822")
return err</span>
}
</pre>
<pre class="file" id="file7" style="display: none">package rest
import (
"context"
"fmt"
"log/slog"
"github.com/KarpelesLab/pjson"
)
// SpotClient is an interface fulfilled by spotlib.Client that provides
// the necessary functionality for making API requests through a Spot connection.
// Using this interface helps avoid dependency loops between packages.
type SpotClient interface {
Query(ctx context.Context, target string, body []byte) ([]byte, error)
}
// SpotApply makes a REST API request through a SpotClient and unmarshals the response into target.
// This is similar to Apply but uses a SpotClient for the request.
//
// Parameters:
//
// - ctx: Context for the request
// - client: SpotClient to use for the API request
// - path: API endpoint path
// - method: HTTP method (GET, POST, PUT, etc.)
// - param: Request parameters or body content
// - target: Destination object for unmarshaled response data
//
// Returns: an error if the request fails or response cannot be unmarshaled.
func SpotApply(ctx context.Context, client SpotClient, path, method string, param any, target any) error <span class="cov0" title="0">{
res, err := SpotDo(ctx, client, path, method, param)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">err = pjson.UnmarshalContext(ctx, res.Data, target)
if Debug && err != nil </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, res.Data), "event", "rest:not_json")
}</span>
<span class="cov0" title="0">return err</span>
}
// SpotAs makes a REST API request through a SpotClient and returns the response data unmarshaled into type T.
// This is a generic version of SpotApply that returns the target object directly.
//
// Parameters:
// - ctx: Context for the request
// - client: SpotClient to use for the API request
// - path: API endpoint path
// - method: HTTP method (GET, POST, PUT, etc.)
// - param: Request parameters or body content
//
// Returns: the unmarshaled object of type T and any error encountered.
func SpotAs[T any](ctx context.Context, client SpotClient, path, method string, param any) (T, error) <span class="cov0" title="0">{
var target T
res, err := SpotDo(ctx, client, path, method, param)
if err != nil </span><span class="cov0" title="0">{
return target, err
}</span>
<span class="cov0" title="0">err = pjson.UnmarshalContext(ctx, res.Data, &target)
if Debug && err != nil </span><span class="cov0" title="0">{
slog.ErrorContext(ctx, fmt.Sprintf("failed to parse json: %s\n%s", err, res.Data), "event", "rest:not_json")
}</span>
<span class="cov0" title="0">return target, err</span>
}
// SpotDo executes a REST API request through a SpotClient and returns the raw Response object.
// This is the base function used by SpotApply and SpotAs.
//
// Parameters:
//
// - ctx: Context for the request
// - client: SpotClient to use for the API request
// - path: API endpoint path
// - method: HTTP method (GET, POST, PUT, etc.)
// - param: Request parameters or body content
//
// Returns: the raw Response object and any error encountered during the request.
func SpotDo(ctx context.Context, client SpotClient, path, method string, param any) (*Response, error) <span class="cov0" title="0">{
req := map[string]any{
"path": path,
"verb": method,
"params": param,
}
buf, err := pjson.Marshal(req)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">respbuf, err := client.Query(ctx, "@/p_api", buf)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">var resp *Response
err = pjson.Unmarshal(respbuf, &resp)
if err != nil </span><span class="cov0" title="0">{
return nil, err
}</span>
<span class="cov0" title="0">return resp, nil</span>
}
</pre>
<pre class="file" id="file8" style="display: none">package rest
import (
"context"
"time"
"github.com/KarpelesLab/pjson"
)
type Time struct {
time.Time
}
type timestampInternal struct {
Unix int64 `json:"unix"` // 1597242491
Usec int64 `json:"us"` // 747497
TZ string `json:"tz,omitempty"` // Asia/Tokyo
ISO string `json:"iso,omitempty"` // "2020-08-12 23:28:11.747497"
Full int64 `json:"full,omitempty,string"` // "1597242491747497"
UnixMS int64 `json:"unixms,omitempty,string"` // "1597242491747"
}
func (u *Time) UnmarshalJSON(data []byte) error <span class="cov0" title="0">{
// Ignore null, like in the main JSON package.
if string(data) == "null" </span><span class="cov0" title="0">{
return nil
}</span>
<span class="cov0" title="0">var sd timestampInternal
err := pjson.Unmarshal(data, &sd)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">u.Time = time.Unix(sd.Unix, sd.Usec*1000) // *1000 means µs → ns
return nil</span>
}
func (u Time) MarshalJSON() ([]byte, error) <span class="cov0" title="0">{
var sd timestampInternal
sd.Unix = u.Unix()
sd.Usec = int64(u.Nanosecond() / 1000)
sd.TZ = u.Location().String()
sd.ISO = u.UTC().Format("2006-01-02 15:04:05")
sd.Full = u.UnixMicro()
sd.UnixMS = u.UnixMilli()
return pjson.Marshal(sd)
}</span>
func (u *Time) UnmarshalContextJSON(ctx context.Context, data []byte) error <span class="cov0" title="0">{
// Ignore null, like in the main JSON package.
if string(data) == "null" </span><span class="cov0" title="0">{
return nil
}</span>
<span class="cov0" title="0">var sd timestampInternal
err := pjson.UnmarshalContext(ctx, data, &sd)
if err != nil </span><span class="cov0" title="0">{
return err
}</span>
<span class="cov0" title="0">u.Time = time.Unix(sd.Unix, sd.Usec*1000) // *1000 means µs → ns
return nil</span>
}
func (u Time) MarshalContextJSON(ctx context.Context) ([]byte, error) <span class="cov0" title="0">{
var sd timestampInternal
sd.Unix = u.Unix()
sd.Usec = int64(u.Nanosecond() / 1000)
sd.TZ = u.Location().String()
sd.ISO = u.UTC().Format("2006-01-02 15:04:05")
sd.Full = u.UnixMicro()
sd.UnixMS = u.UnixMilli()
return pjson.MarshalContext(ctx, sd)
}</span>
</pre>
<pre class="file" id="file9" style="display: none">package rest
import (
"context"
"errors"
)
// Token represents an OAuth2 token with refresh capabilities.
// It contains both access and refresh tokens and methods to use them in requests.
type Token struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
Type string `json:"token_type"`
ClientID string
Expires int `json:"expires_in"`
}
// tokenValue is a type used as a context key for token storage.
type tokenValue int
// withToken is a context wrapper that holds a token value.
type withToken struct {
context.Context
token *Token
}
var (
// ErrNoClientID is returned when token renewal is attempted without a client ID
ErrNoClientID = errors.New("no client_id has been provided for token renewal")
// ErrNoRefreshToken is returned when token renewal is attempted without a refresh token
ErrNoRefreshToken = errors.New("no refresh token is available and access token has expired")
)
// Value implements the context.Context Value method for withToken.
// It returns the token for tokenValue keys and delegates to the parent context otherwise.
func (w *withToken) Value(v any) any <span class="cov0" title="0">{
if _, ok := v.(tokenValue); ok </span><span class="cov0" title="0">{
return w.token
}</span>
<span class="cov0" title="0">return w.Context.Value(v)</span>
}