/
api.go
68 lines (56 loc) · 1.31 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
package main
import (
"encoding/json"
"fmt"
"github.com/evilsocket/islazy/log"
"github.com/evilsocket/shieldwall/firewall"
"github.com/evilsocket/shieldwall/version"
"net/http"
"runtime"
"strings"
"time"
)
// API client
type API struct {
config APIConfig
}
func NewAPI(config APIConfig) *API {
return &API{
config: config,
}
}
func (a API) FetchRules() ([]firewall.Rule, error) {
client := &http.Client{}
if a.config.Timeout > 0 {
client.Timeout = time.Duration(a.config.Timeout) * time.Second
}
if strings.Index(a.config.Server, "://") == -1 {
a.config.Server = "https://" + a.config.Server
}
url := fmt.Sprintf("%s/api/v1/rules", a.config.Server)
log.Debug("polling %s", url)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
// agent authentication
req.Header.Set("X-ShieldWall-Agent-Token", a.config.Token)
req.Header.Set("User-Agent", fmt.Sprintf(
"ShieldWall Agent v%s (%s %s)",
version.Version,
runtime.GOOS,
runtime.GOARCH))
res, err := client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%d (%s)", res.StatusCode, res.Status)
}
var rules []firewall.Rule
if err = json.NewDecoder(res.Body).Decode(&rules); err != nil {
return nil, err
}
return rules, nil
}