-
Notifications
You must be signed in to change notification settings - Fork 6
/
http.go
102 lines (82 loc) · 2.16 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package micha
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
)
// HttpClient interface
type HttpClient interface {
Do(*http.Request) (*http.Response, error)
}
type HTTPError struct {
StatusCode int
}
func (e HTTPError) Error() string {
return fmt.Sprintf("http status %d (%s)", e.StatusCode, http.StatusText(e.StatusCode))
}
type fileField struct {
Source io.Reader
Fieldname string
Filename string
}
func handleResponse(response *http.Response) ([]byte, error) {
defer response.Body.Close()
if response.StatusCode > http.StatusBadRequest {
return nil, HTTPError{response.StatusCode}
}
return io.ReadAll(response.Body)
}
func newGetRequest(ctx context.Context, url string, params url.Values) (*http.Request, error) {
if params != nil {
url += fmt.Sprintf("?%s", params.Encode())
}
return http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
}
func newPostRequest(ctx context.Context, url string, data interface{}) (*http.Request, error) {
body := new(bytes.Buffer)
if data != nil {
if err := json.NewEncoder(body).Encode(data); err != nil {
return nil, fmt.Errorf("encode data error: %w", err)
}
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", "application/json")
return request, nil
}
func newMultipartRequest(ctx context.Context, url string, file *fileField, params url.Values) (*http.Request, error) {
body := new(bytes.Buffer)
writer := multipart.NewWriter(body)
if file != nil {
part, err := writer.CreateFormFile(file.Fieldname, file.Filename)
if err != nil {
return nil, err
}
if _, err := io.Copy(part, file.Source); err != nil {
return nil, err
}
}
for field, values := range params {
for i := range values {
if err := writer.WriteField(field, values[i]); err != nil {
return nil, err
}
}
}
if err := writer.Close(); err != nil {
return nil, err
}
request, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
if err != nil {
return nil, err
}
request.Header.Add("Content-Type", writer.FormDataContentType())
return request, nil
}