-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
121 lines (100 loc) · 2.65 KB
/
main.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"github.com/maxmind/mmdbwriter"
"github.com/maxmind/mmdbwriter/mmdbtype"
)
type Aws_ranges struct {
SyncToken string `json:"syncToken"`
CreateDate string `json:"createDate"`
Prefixes []struct {
IPPrefix string `json:"ip_prefix"`
Region string `json:"region"`
Service string `json:"service"`
NetworkBorderGroup string `json:"network_border_group"`
} `json:"prefixes"`
Ipv6Prefixes []struct {
Ipv6Prefix string `json:"ipv6_prefix"`
Region string `json:"region"`
Service string `json:"service"`
NetworkBorderGroup string `json:"network_border_group"`
} `json:"ipv6_prefixes"`
}
func main() {
url := "https://ip-ranges.amazonaws.com/ip-ranges.json"
writer, err := mmdbwriter.New(
mmdbwriter.Options{
DatabaseType: "AWS-IP-RANGES",
RecordSize: 24,
},
)
if err != nil {
fmt.Println("Cannot start mmdbwriter")
log.Fatal(err)
}
resp, err := http.Get(url)
if err != nil {
fmt.Println("Cannot download ip-ranges.json")
log.Fatal(err)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Cannot read content of ip-ranges.json")
log.Fatal(err)
}
var result Aws_ranges
if err := json.Unmarshal(body, &result); err != nil {
fmt.Println("Cannot parse json from ip-ranges.json")
log.Fatal(err)
}
for _, rec := range result.Prefixes {
_, network, err := net.ParseCIDR(rec.IPPrefix)
if err != nil {
fmt.Println("ip_prefix is not valid")
log.Fatal(err)
}
record := mmdbtype.Map{}
record["region"] = mmdbtype.String(rec.Region)
record["service"] = mmdbtype.String(rec.Service)
record["network_border_group"] = mmdbtype.String(rec.NetworkBorderGroup)
err = writer.Insert(network, record)
if err != nil {
fmt.Println("Cannot insert a record into mmdb file")
log.Fatal(err)
}
}
for _, rec := range result.Ipv6Prefixes {
_, network, err := net.ParseCIDR(rec.Ipv6Prefix)
if err != nil {
log.Fatal(err)
message := fmt.Sprintf("ParseCIDR error")
return &message, err
}
record := mmdbtype.Map{}
record["region"] = mmdbtype.String(rec.Region)
record["service"] = mmdbtype.String(rec.Service)
record["network_border_group"] = mmdbtype.String(rec.NetworkBorderGroup)
err = writer.Insert(network, record)
if err != nil {
log.Fatal(err)
message := fmt.Sprintf("Insert error")
return &message, err
}
}
fh, err := os.Create("aws.mmdb")
if err != nil {
fmt.Println("Cannot create output file")
log.Fatal(err)
}
_, err = writer.WriteTo(fh)
if err != nil {
fmt.Println("Cannot save output file")
log.Fatal(err)
}
}