-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
84 lines (76 loc) · 1.49 KB
/
request.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 goixc
import (
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
)
type Request struct {
*Client
Form string
Body interface{}
Listar bool
}
func (c *Client) Get(form string, body interface{}) *Request {
return &Request{
Client: c,
Form: form,
Body: body,
}
}
func (c *Client) List(form string, body interface{}) *Request {
return &Request{
Client: c,
Form: form,
Body: body,
Listar: true,
}
}
func (c *Request) Run(ctx context.Context) ([]byte, error) {
reqBody, err := c.bodyReader()
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, "POST", c.url(), reqBody)
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
req.Header.Set("Content-Type", "application/json")
if c.Listar {
req.Header.Set("ixcsoft", "listar")
}
resp, err := c.http.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
func (c *Request) RunJSON(ctx context.Context, respJSON interface{}) error {
respBody, err := c.Run(ctx)
if err != nil {
return err
}
err = json.Unmarshal(respBody, respJSON)
if err != nil {
return &InvalidJSONError{respBody, err}
}
return nil
}
func (c *Request) url() string {
return c.formURL(c.Form)
}
func (c *Request) bodyReader() (io.Reader, error) {
b, ok := c.Body.([]byte)
if ok {
return bytes.NewReader(b), nil
}
b, err := json.Marshal(c.Body)
if err != nil {
return nil, err
}
return bytes.NewReader(b), nil
}