-
Notifications
You must be signed in to change notification settings - Fork 2
/
censys.go
88 lines (69 loc) · 1.98 KB
/
censys.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
package gocensys
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
)
const (
// BaseURL represents the Censys version 1 API URL.
BaseURL = "https://www.censys.io/api/v1"
)
// CensysAPI represents a censys API client used for accessing available endpoints.
type CensysAPI struct {
// HTTPClient is the HTTP client that will be used in the API requests.
HTTPClient *http.Client
// UID represents your API key.
UID string
// Secret is required for accessing the API.
Secret string
}
// NewCensysAPI takes user specific API ID (uid), secret and returns a CensysAPI struct for that user.
func NewCensysAPI(uid, secret string, httpClient *http.Client) *CensysAPI {
return &CensysAPI{
HTTPClient: http.DefaultClient,
UID: uid,
Secret: secret,
}
}
// apiGet performs "GET" requests on the specified endpoint.
func (c CensysAPI) apiGet(endpoint string, form url.Values, data interface{}) error {
req, err := http.NewRequest("GET", BaseURL+endpoint, nil)
if err != nil {
return err
}
req.SetBasicAuth(c.UID, c.Secret)
req.Form = form
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return decodeResponse(resp, data)
}
// apiPost performs "POST" requests on the specified endpoint.
func (c CensysAPI) apiPost(endpoint string, query map[string]interface{}, data interface{}) error {
jsonStr, err := json.Marshal(query)
if err != nil {
return err
}
req, err := http.NewRequest("POST", BaseURL+endpoint, bytes.NewBuffer(jsonStr))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
req.SetBasicAuth(c.UID, c.Secret)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return decodeResponse(resp, data)
}
// decodeResponse unmarshals the a json file into a Go struct
func decodeResponse(resp *http.Response, data interface{}) error {
if resp.StatusCode != http.StatusOK {
return newAPIError(resp)
}
return json.NewDecoder(resp.Body).Decode(data)
}