-
Notifications
You must be signed in to change notification settings - Fork 2
/
http.go
84 lines (68 loc) · 1.52 KB
/
http.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
package psn
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
type headers map[string]string
func (p *psn) post(ctx context.Context, formData url.Values, url string, headers headers, value interface{}) error {
req, err := http.NewRequestWithContext(
ctx,
"POST",
url,
strings.NewReader(formData.Encode()),
)
if err != nil {
return fmt.Errorf("can't create new POST request %w: ", err)
}
for k, v := range headers {
req.Header.Add(k, v)
}
resp, err := p.http.Do(req)
if err != nil {
return fmt.Errorf("can't execute POST request %w: ", err)
}
defer func() {
err = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad request")
}
err = json.NewDecoder(resp.Body).Decode(&value)
if err != nil {
return fmt.Errorf("can't decode POST request %w: ", err)
}
return nil
}
func (p *psn) get(ctx context.Context, url string, headers headers, value interface{}) error {
req, err := http.NewRequestWithContext(
ctx,
"GET",
url,
nil,
)
if err != nil {
return fmt.Errorf("can't create new GET request %w: ", err)
}
for k, v := range headers {
req.Header.Add(k, v)
}
resp, err := p.http.Do(req)
if err != nil {
return fmt.Errorf("can't execute GET request %w: ", err)
}
defer func() {
err = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("bad request")
}
err = json.NewDecoder(resp.Body).Decode(&value)
if err != nil {
return fmt.Errorf("can't decode POST request %w: ", err)
}
return nil
}