-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
107 lines (95 loc) · 2.36 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
103
104
105
106
107
package sharefile
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
)
type Login struct {
Credentials
}
type Credentials interface {
Account() Account
Do(*http.Request) (*http.Response, error)
}
func (login Login) doPost(ctx context.Context, url string, send, recv interface{}) error {
body, err := toBody(send)
if err != nil {
return fmt.Errorf("Failed to serialize body: %v", err)
}
req, err := http.NewRequest("POST", url, body)
if err != nil {
return fmt.Errorf("Failed to create post request: %v", err)
}
req.Header.Add("Content-Type", "application/json")
return login.do(ctx, req, recv)
}
func (login Login) doPatch(ctx context.Context, url string, send, recv interface{}) error {
body, err := toBody(send)
if err != nil {
return fmt.Errorf("Failed to serialize body: %v", err)
}
req, err := http.NewRequest("PATCH", url, body)
if err != nil {
return fmt.Errorf("Failed to create patch request: %v", err)
}
req.Header.Add("Content-Type", "application/json")
return login.do(ctx, req, recv)
}
func (login *Login) doDelete(ctx context.Context, url string) error {
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
return fmt.Errorf("Failed to create delete request: %v", err)
}
err = login.do(ctx, req, nil)
// no no no
if strings.HasPrefix(err.Error(), strconv.Itoa(http.StatusNoContent)) {
return nil
}
return err
}
func toBody(send interface{}) (io.Reader, error) {
var body io.Reader
if send != nil {
b, err := json.Marshal(send)
if err != nil {
return nil, err
}
body = bytes.NewReader(b)
}
return body, nil
}
func (login *Login) doGet(ctx context.Context, url string, recv interface{}) error {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
return login.do(ctx, req, recv)
}
func (login *Login) do(ctx context.Context, req *http.Request, recv interface{}) error {
// log.dbg this through context
// b, _ := httputil.DumpRequestOut(req, req.Method != "GET")
// fmt.Println(string(b))
resp, err := login.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// b, _ = httputil.DumpResponse(resp, true)
// fmt.Println(string(b))
if resp.StatusCode != http.StatusOK {
return errors.New(resp.Status)
}
if recv != nil {
err = json.NewDecoder(resp.Body).Decode(recv)
if err != nil {
return err
}
}
return nil
}