forked from dizel-by/ripego
-
Notifications
You must be signed in to change notification settings - Fork 1
/
gen.go
110 lines (91 loc) · 2.24 KB
/
gen.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
// The following directive is necessary to make the package coherent:
// +build ignore
// This program generates ipv4_address_space.go. It can be invoked by running
// go generate
package main
import (
"encoding/xml"
"log"
"net/http"
"os"
"strconv"
"text/template"
"time"
)
type Registry struct {
Record []Record `xml:"record"`
}
type Record struct {
Prefix string `xml:"prefix"`
Whois string `xml:"whois"`
}
func main() {
generate(tplV4, "ipv4_address_space.go", "https://www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xml")
generate(tplV6, "ipv6_address_space.go", "https://www.iana.org/assignments/ipv6-unicast-address-assignments/ipv6-unicast-address-assignments.xml")
}
func generate(genFun func(*Registry, *os.File), filename, url string) {
rsp, err := http.Get(url)
die(err)
defer rsp.Body.Close()
registry := Registry{}
die(xml.NewDecoder(rsp.Body).Decode(®istry))
file, err := os.Create(filename)
die(err)
defer file.Close()
header.Execute(file, struct {
Timestamp time.Time
URL string
}{
Timestamp: time.Now(),
URL: url,
})
genFun(®istry, file)
}
func tplV4(reg *Registry, file *os.File) {
var prefixes [256]string
for _, record := range reg.Record {
if len(record.Prefix) != 5 || record.Prefix[3:5] != "/8" {
panic("invalid prefix: " + record.Prefix)
}
octet, _ := strconv.Atoi(record.Prefix[0:3])
prefixes[octet] = record.Whois
}
die(ipv4template.Execute(file, prefixes))
}
func tplV6(reg *Registry, file *os.File) {
list := make(map[string]string)
for _, record := range reg.Record {
if record.Whois != "" {
list[record.Prefix] = record.Whois
}
}
die(ipv6template.Execute(file, list))
}
func die(err error) {
if err != nil {
log.Fatal(err)
}
}
var (
header = template.Must(template.New("").Parse(`// Code generated by go generate; DO NOT EDIT.
// This file was generated by robots at
// {{ .Timestamp }}
// using data from
// {{ .URL }}
package ripego
`))
ipv4template = template.Must(template.New("").Parse(`
var ipv4prefixes = []string{
{{- range . }}
{{ printf "%q" . }},
{{- end }}
}
`))
ipv6template = template.Must(template.New("").Parse(`
func initIPv6(){
{{- range $key, $val := . }}
addIPv6Prefix({{ printf "%q, %q" $key $val }})
{{- end }}
}
`))
)