-
Notifications
You must be signed in to change notification settings - Fork 2
/
driver.go
83 lines (66 loc) · 1.56 KB
/
driver.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
package misp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/http/httputil"
"net/url"
"os"
)
// NewRequest prepares http.Request to call the MISP API
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.baseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", c.Key)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", "dutchcoders/gomisp")
return req, nil
}
// Do will execute the http.Request and decode the result
func (wd *Client) Do(req *http.Request, v interface{}) error {
if !wd.debug {
} else if dump, err := httputil.DumpRequestOut(req, false); err == nil {
os.Stdout.Write(dump)
}
resp, err := wd.Client.Do(req)
if err != nil {
return err
}
r := resp.Body
defer r.Close()
if !wd.debug {
} else if dump, err := httputil.DumpResponse(resp, true); err == nil {
os.Stdout.Write(dump)
resp.Body = ioutil.NopCloser(bytes.NewBuffer(dump))
}
r2 := r
if resp.StatusCode != http.StatusOK {
result := ErrorResult{}
json.NewDecoder(r2).Decode(&result)
return fmt.Errorf(result.Error)
}
err = json.NewDecoder(r2).Decode(&v)
if err != nil {
return err
}
return nil
}