-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClient.go
92 lines (80 loc) · 1.96 KB
/
Client.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
package OtxApiClient
import (
"errors"
"io"
"log"
"net/http"
)
type Client struct {
httpClient *http.Client
userAgent string
apiKey string
baseUrl string
}
type OtxOpt func(client *Client) error
func NewClient(apiKey string, opts ...OtxOpt) (*Client, error) {
client := &Client{
httpClient: http.DefaultClient,
userAgent: "Go-OtxApiClient",
apiKey: apiKey,
baseUrl: "https://otx.alienvault.com/api/v1",
}
for _, opt := range opts {
err := opt(client)
if err != nil {
return nil, err
}
}
return client, nil
}
func (client *Client) GetIndicatorsService() *indicatorsService {
return &indicatorsService{client: client}
}
func (client *Client) GetUserService() *userService {
return &userService{client: client}
}
func (client *Client) GetPulsesService() *pulsesService {
return &pulsesService{client: client}
}
func (client *Client) doHttpRequest(method string, path string, body io.Reader) (*http.Response, error) {
url := client.baseUrl + path
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("X-OTX-API-KEY", client.apiKey)
req.Header.Set("User-Agent", client.userAgent)
req.Header.Set("Content-Type", "application/json")
log.Println(url, req)
return client.httpClient.Do(req)
}
var ErrNoHttpClient = errors.New("no http client")
var ErrNoUserAgent = errors.New("no user-agent")
var ErrNoBaseUrl = errors.New("no base url")
func WithHttpClient(httpClient *http.Client) OtxOpt {
return func(client *Client) error {
if httpClient == nil {
return ErrNoHttpClient
}
client.httpClient = httpClient
return nil
}
}
func WithUserAgent(userAgent string) OtxOpt {
return func(client *Client) error {
if len(userAgent) < 1 {
return ErrNoUserAgent
}
client.userAgent = userAgent
return nil
}
}
func WithBaseUrl(baseUrl string) OtxOpt {
return func(client *Client) error {
if len(baseUrl) < 1 {
return ErrNoBaseUrl
}
client.baseUrl = baseUrl
return nil
}
}