forked from crowdsecurity/crowdsec
/
api.go
84 lines (74 loc) · 2.17 KB
/
api.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 metabase
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/asians-cloud/crowdsec/pkg/cwversion"
"github.com/dghubble/sling"
log "github.com/sirupsen/logrus"
)
type APIClient struct {
CTX *sling.Sling
Client *http.Client
}
const (
sessionEndpoint = "login"
scanEndpoint = "scan"
resetPasswordEndpoint = "reset_password"
userEndpoint = "user"
databaseEndpoint = "database"
)
var (
routes = map[string]string{
sessionEndpoint: "api/session",
scanEndpoint: "api/database/2/rescan_values",
resetPasswordEndpoint: "api/user/1/password",
userEndpoint: "api/user/1",
databaseEndpoint: "api/database/2",
}
)
func NewAPIClient(url string) (*APIClient, error) {
httpClient := &http.Client{Timeout: 20 * time.Second}
return &APIClient{
CTX: sling.New().Client(httpClient).Base(url).Set("User-Agent", fmt.Sprintf("crowdsec/%s", cwversion.VersionStr())),
Client: httpClient,
}, nil
}
func (h *APIClient) Do(method string, route string, body interface{}) (interface{}, interface{}, error) {
var Success interface{}
var Error interface{}
var resp *http.Response
var err error
var data []byte
if body != nil {
data, _ = json.Marshal(body)
}
switch method {
case "POST":
log.Debugf("POST /%s", route)
log.Debugf("%s", string(data))
resp, err = h.CTX.New().Post(route).BodyJSON(body).Receive(&Success, &Error)
case "GET":
log.Debugf("GET /%s", route)
resp, err = h.CTX.New().Get(route).Receive(&Success, &Error)
case "PUT":
log.Debugf("PUT /%s", route)
log.Debugf("%s", string(data))
resp, err = h.CTX.New().Put(route).BodyJSON(body).Receive(&Success, &Error)
case "DELETE":
default:
return nil, nil, fmt.Errorf("unsupported method '%s'", method)
}
if Error != nil {
return Success, Error, fmt.Errorf("http error: %v", Error)
}
if resp != nil && resp.StatusCode != 200 && resp.StatusCode != 202 {
return Success, Error, fmt.Errorf("bad status code '%d': (success: %+v) | (error: %+v)", resp.StatusCode, Success, Error)
}
return Success, Error, err
}
// Set set headers as key:value
func (h *APIClient) Set(key string, value string) {
h.CTX = h.CTX.Set(key, value)
}