-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
103 lines (92 loc) · 2.24 KB
/
main.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"text/tabwriter"
"time"
"github.com/LeandroLS/valoop"
"github.com/gomarkdown/markdown"
"golang.org/x/net/html"
)
type BadLink struct {
url string
statusCode int
}
func main() {
markDown, err := os.ReadFile("README.md")
handleErr(err)
htmlBytes := markdown.ToHTML(markDown, nil, nil)
bReader := bytes.NewReader(htmlBytes)
htmlParsed, err := html.Parse(bReader)
handleErr(err)
links := getHtmlTags(htmlParsed, "a", "href", nil)
if len(links) < 1 {
fmt.Println("No links found.")
return
}
badLinks := getBadLinks(links)
if len(badLinks) < 1 {
fmt.Println("All links works.")
return
}
logBadLinksFound(os.Stdout, badLinks)
os.Exit(1)
}
func getAllowedStatusCodes() []int {
statusCodesJson := os.Getenv("INPUT_ALLOWEDSTATUSCODES")
var statusCodeArr []int
err := json.Unmarshal([]byte(statusCodesJson), &statusCodeArr)
handleErr(err)
statusCodeArr = append(statusCodeArr, 200)
return statusCodeArr
}
func getBadLinks(links []string) []BadLink {
statusCodesArr := getAllowedStatusCodes()
var badLinks []BadLink
ms, _ := time.ParseDuration("0.35s")
for i := 0; i < len(links); i++ {
resp, err := http.Get(links[i])
if err != nil {
badLinks = append(badLinks, BadLink{links[i], 0})
continue
}
defer resp.Body.Close()
if !valoop.IntSliceContains(statusCodesArr, resp.StatusCode) {
badLinks = append(badLinks, BadLink{links[i], resp.StatusCode})
}
time.Sleep(ms)
}
return badLinks
}
func getHtmlTags(n *html.Node, rawHtmlTag string, htmlTagKey string, tags []string) []string {
if n.Type == html.ElementNode && n.Data == rawHtmlTag {
for _, a := range n.Attr {
if a.Key == htmlTagKey {
tags = append(tags, a.Val)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
tags = getHtmlTags(c, rawHtmlTag, htmlTagKey, tags)
}
return tags
}
func handleErr(e error) {
if e != nil {
panic(e)
}
}
func logBadLinksFound(writer io.Writer, links []BadLink) {
w := tabwriter.NewWriter(writer, 0, 8, 2, ' ', 0)
format := "%v\t%v\n"
fmt.Fprintf(w, format, "Site", "Status Code")
fmt.Fprintf(w, format, "----", "-----------")
for _, link := range links {
fmt.Fprintf(w, format, link.url, link.statusCode)
}
w.Flush()
}