-
Notifications
You must be signed in to change notification settings - Fork 4
/
helpers.go
249 lines (207 loc) · 5.16 KB
/
helpers.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package main
import (
//"flag"
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"
"mvdan.cc/xurls/v2"
)
type Post struct {
ID string
URL string
}
// extract all urls from the string and return them as a slice (array)
func extractURL(str string) []string {
rxStrict := xurls.Strict()
foundUrls := rxStrict.FindAllString(str, -1)
return foundUrls
}
func parseFromTelescope() []string {
var allPostBody []byte
resp, err := http.Get("http://localhost:3000/posts")
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var posts []Post
if err := json.Unmarshal(body, &posts); err != nil {
panic(err)
}
for _, post := range posts {
resp, err := http.Get("http://localhost:3000" + post.URL)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
allPostBody = append(allPostBody, body...)
}
return extractURL(string(allPostBody))
}
//Function to parse ignore URLs from provided ignore file path
func parseIgnoreURL(ignoreFilePath string) []string {
var ignoreURLs []string
//Read the content of file given by ignoreFilePath
content, err := ioutil.ReadFile(ignoreFilePath)
if err != nil {
log.Fatal(err)
}
//Create a scanner for file content
scanner := bufio.NewScanner(strings.NewReader(string(content)))
re := regexp.MustCompile("^(#|https?://)")
//Scan the ignore URL file line by line
for scanner.Scan() {
line := scanner.Text()
//Check if the ignore link file is invalid
if !re.Match([]byte(line)) {
fmt.Println("Ignore Link File is invalid")
fmt.Println("Exit with status 1")
os.Exit(1)
}
firstChar := string(line[0])
//Only look at lines that don't start with #
if firstChar != "#" {
URLsFoundFromLine := extractURL(line)
ignoreURLs = append(ignoreURLs, URLsFoundFromLine...)
}
}
//If there is error during scan, log the error
if scanErr := scanner.Err(); scanErr != nil {
log.Fatal(scanErr)
}
return ignoreURLs
}
// remove duplicate strings from a slice of strings
func removeDuplicate(urls []string) []string {
result := make([]string, 0, len(urls))
temp := map[string]struct{}{}
for _, item := range urls {
if _, ok := temp[item]; !ok {
temp[item] = struct{}{}
result = append(result, item)
}
}
return result
}
func parseUniqueURLsFromFile(filepath string) []string {
//open file and read it
content, err := ioutil.ReadFile(filepath)
if err != nil {
log.Fatal(err)
}
textContent := string(content)
//call functions to check the availability of each url
return removeDuplicate(extractURL(textContent))
}
// get the status code from a link.
func getStatusCode(link string) (int, error) {
client := http.Client{
Timeout: 8 * time.Second,
}
resp, err := client.Head(link)
if err != nil {
return -1, err
}
return resp.StatusCode, nil
}
//check if urls passed reachable or not
func checkURL(urls []string) {
//use multi-threads to make the process execute faster
var wg sync.WaitGroup
wg.Add(len(urls))
//loop through the urls to check one by one
for _, v := range urls {
//annonymous function to make the wg.Done() work
go func(v string) {
defer wg.Done()
statusCode, err := getStatusCode(v)
//deal with errors
if err != nil {
fmt.Println(v + ": NO RESPONCE!")
} else {
//allow environment variables to determine the colors of the output
clicolor := os.Getenv("CLICOLOR")
if clicolor == "1" {
//set different colors and reponse according to different status code
var (
greenC = "\033[1;32m%s\033[0m"
redC = "\033[1;31m%s\033[0m"
grayC = "\033[1;30m%s\033[0m"
)
switch statusCode {
case 200:
fmt.Printf(greenC, v+": GOOD!\n")
case 400, 404:
fmt.Printf(redC, v+": BAD!\n")
default:
fmt.Printf(grayC, v+": UNKNOWN!\n")
}
} else {
switch statusCode {
case 200:
fmt.Println(v + ": GOOD!")
case 400, 404:
fmt.Println(v + ": BAD!")
default:
fmt.Println(v + ": UNKNOWN!")
}
}
}
}(v)
}
wg.Wait()
}
//json output structure
type UrlJson struct {
//[ { "url": 'https://www.google.com', "status": 200 }, { "url": 'https://bad-link.com', "status": 404 } ]
Url string
Status int
}
//if json output required, check urls and output json
func checkURLJson(urls []string) {
//use multi-threads to make the process execute faster
var wg sync.WaitGroup
wg.Add(len(urls))
urlsJ := make([]UrlJson, 0)
//loop through the urls to check one by one
for _, v := range urls {
go func(v string) {
defer wg.Done()
client := http.Client{
Timeout: 8 * time.Second,
}
//check if the url is reachable or not
resp, err := client.Head(v)
//deal with errors
if err != nil {
j := UrlJson{v, -1}
urlsJ = append(urlsJ, j)
} else {
u := UrlJson{v, resp.StatusCode}
urlsJ = append(urlsJ, u)
}
}(v)
}
wg.Wait()
urlsInJson, err := json.Marshal(urlsJ)
if err != nil {
log.Fatalf("Something is going wrong with json Marshalling: %s", err)
}
//fmt.Println(urlsInJson)
os.Stdout.WriteString(string(urlsInJson))
}