-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhttp.go
More file actions
83 lines (74 loc) · 1.77 KB
/
Copy pathhttp.go
File metadata and controls
83 lines (74 loc) · 1.77 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
package subtitles
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const maxBody = 32 << 20 // subtitle archives are small
func defaultClient(c *http.Client) *http.Client {
if c != nil {
return c
}
return &http.Client{Timeout: 60 * time.Second}
}
func do(ctx context.Context, c *http.Client, req *http.Request, h http.Header) ([]byte, error) {
for k, vs := range h {
for _, v := range vs {
req.Header.Set(k, v)
}
}
resp, err := defaultClient(c).Do(req.WithContext(ctx))
if err != nil {
return nil, err
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, maxBody))
if err != nil {
return nil, err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("%s: %s: %s", req.URL.Host, resp.Status, snippet(data))
}
return data, nil
}
func getBytes(ctx context.Context, c *http.Client, url string, h http.Header) ([]byte, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
return do(ctx, c, req, h)
}
func getJSON(ctx context.Context, c *http.Client, url string, h http.Header, out any) error {
data, err := getBytes(ctx, c, url, h)
if err != nil {
return err
}
return json.Unmarshal(data, out)
}
func postBytes(ctx context.Context, c *http.Client, url string, h http.Header, in any) ([]byte, error) {
payload, err := json.Marshal(in)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, url, bytes.NewReader(payload))
if err != nil {
return nil, err
}
if h == nil {
h = http.Header{}
}
if h.Get("Content-Type") == "" {
h.Set("Content-Type", "application/json")
}
return do(ctx, c, req, h)
}
func snippet(b []byte) string {
if len(b) > 200 {
b = b[:200]
}
return string(bytes.TrimSpace(b))
}