-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgfwlist.go
115 lines (102 loc) · 2.19 KB
/
gfwlist.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
package main
import (
"bufio"
"encoding/base64"
"fmt"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
"time"
)
func getGFWlist() []string {
var gfwlistFile = config.ConfigDir + "/gfwlist.txt"
f, err := os.Stat(gfwlistFile)
var needFetch, needUpdate = false, false
if err != nil {
if os.IsNotExist(err) {
needFetch = true
}
} else if f.ModTime().Before(time.Now().AddDate(0, 0, -1)) {
needUpdate = true
}
if needFetch {
fmt.Println("首次下载gfwlist.txt")
fetchGFWlist()
}
fl, err := os.Open(gfwlistFile)
if err != nil {
panic(err)
}
defer fl.Close()
buf := bufio.NewReader(fl)
var urlList []string
for {
line, err := buf.ReadString('\n')
if err != nil {
break
}
line = strings.TrimSpace(line)
if len(line) > 0 {
urlList = append(urlList, line)
}
}
if needUpdate {
fmt.Println("重新下载gfwlist.txt")
go fetchGFWlist()
}
return urlList
}
func fetchGFWlist() {
var gfwUrl = "https://raw.githubusercontent.com/gfwlist/gfwlist/master/gfwlist.txt"
//var gfwUrl = "http://127.0.0.1:8081/gfwlist.txt"
resp, err := http.Get(gfwUrl)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
data, err := base64.StdEncoding.DecodeString(string(body))
urlList := strings.Split(string(data), "\n")
newUrlList := parseGFWlist(urlList)
f, err := os.Create(config.ConfigDir + "/gfwlist.txt")
if err != nil {
panic(err)
}
defer f.Close()
for _, line := range newUrlList {
f.WriteString(line + "\n")
}
}
func parseGFWlist(urlList []string) []string {
var newUrlList []string
for _, line := range urlList {
//过滤空行
if len(line) == 0 {
continue
}
//过滤注释和直连的
match, err := regexp.MatchString("^[!,\\[,@].*", line)
if err != nil || match {
continue
}
//过滤关键字类型的 不含点的
match, err = regexp.MatchString("[\\.]", line)
if err != nil || !match {
continue
}
//过滤链接
match, err = regexp.MatchString("[\\/]", line)
if err != nil || match {
continue
}
//转换
reg, err := regexp.Compile("^\\|{1,2}|^\\.")
if err != nil {
continue
}
newUrlList = append(newUrlList, reg.ReplaceAllString(line, ""))
}
return newUrlList
}