-
Notifications
You must be signed in to change notification settings - Fork 11
/
chnroutes_generate.go
79 lines (70 loc) · 1.49 KB
/
chnroutes_generate.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
// +build ignore
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
"text/template"
"time"
)
var apnicGlobalFile = "apnic.txt"
var chnrouteTmplate = template.Must(
template.New("").Parse(
`// Code generated by go generate; DO NOT EDIT.
package main
var ChnroutesTS = "{{ .Timestamp.Format "2006-01-02T15:04:05+0000" }}"
var Chnroutes = []string{
{{- range .Routes }}
{{ printf "%q" . }},
{{- end }}
}
`))
func ipStartCountToCIDR(ipStart string, ipCount int) string {
result := math.Log2(float64(ipCount))
return fmt.Sprintf("%s/%d", ipStart, 32-int(result))
}
func genChnroute() ([]string, error) {
f, err := os.Open(apnicGlobalFile)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
result := make([]string, 0, 8000) // 8000 is a approximate number of cn cidr numbers
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "apnic|CN|ipv4") {
record := strings.FieldsFunc(line,
func(c rune) bool {
return c == '|'
})
ipCount, err := strconv.Atoi(record[4])
if err != nil {
return nil, err
}
result = append(result, ipStartCountToCIDR(record[3], ipCount))
}
}
return result, nil
}
func main() {
routes, err := genChnroute()
if err != nil {
panic(err)
}
f, err := os.Create("chnroutes.go")
if err != nil {
panic(err)
}
defer f.Close()
chnrouteTmplate.Execute(f, struct {
Timestamp time.Time
Routes []string
}{
Timestamp: time.Now().UTC(),
Routes: routes,
})
}