-
Notifications
You must be signed in to change notification settings - Fork 4
/
helpers.go
82 lines (69 loc) · 2 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
package utils
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/gookit/color"
"github.com/tonyvugithub/GoURLsCheckerCLI/models"
)
//ReadFromFile to read a file and converse to string data
func ReadFromFile(filename string) string {
data, err := ioutil.ReadFile(filename)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
return string(data)
}
//CheckLink to validate the link status
func CheckLink(link string, c chan models.LinkStatus, userAgent string) {
client := &http.Client{
Timeout: 2 * time.Second,
}
req, err := http.NewRequest("HEAD", link, nil)
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
color.Gray.Println("[ERROR] " + link)
ls := models.LinkStatus{}
ls.SetURL(link)
ls.SetLiveStatus(false)
c <- ls
return
}
clicolorEnv := os.Getenv("CLICOLOR")
if clicolorEnv == "0" {
checkLinkNoColor(resp, link)
} else if clicolorEnv == "1" || clicolorEnv == "" {
checkLinkWithColor(resp, link)
}
ls := models.LinkStatus{}
ls.SetURL(link)
ls.SetLiveStatus(true)
c <- ls
}
//checkLinkWithColor to output result of link checking with color if "CLICOLOR" option turned on
func checkLinkWithColor(resp *http.Response, link string) {
statusFormatted := "[" + fmt.Sprint(resp.StatusCode, " ", http.StatusText(resp.StatusCode)) + "]"
if resp.StatusCode == 200 {
color.Green.Println(statusFormatted, link)
} else if resp.StatusCode == 400 || resp.StatusCode == 404 {
color.Red.Println(statusFormatted, link)
} else {
color.Gray.Println(statusFormatted, link)
}
}
//checkLinkNoColor to output result of link checking with no color if "CLICOLOR" option turned off
func checkLinkNoColor(resp *http.Response, link string) {
statusFormatted := "[" + fmt.Sprint(resp.StatusCode, " ", http.StatusText(resp.StatusCode)) + "]"
if resp.StatusCode == 200 {
fmt.Println(statusFormatted, link)
} else if resp.StatusCode == 400 || resp.StatusCode == 404 {
fmt.Println(statusFormatted, link)
} else {
fmt.Println(statusFormatted, link)
}
}