-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (92 loc) · 1.83 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
104
105
106
107
108
109
110
package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/BurntSushi/toml"
)
type Config struct {
Sites []*Site `toml:"site"`
}
type Site struct {
Url string `toml:"url"`
Pattern string `toml:"pattern"`
}
type Result struct {
Url string
Error error
Duration float64
}
func checkForPattern(body string, pattern string) (check bool) {
if strings.Contains(body, pattern) {
check = true
} else {
check = false
}
return
}
func getConfig(f string) (c Config) {
if _, err := os.Stat(f); err != nil {
log.Fatal(err)
}
_, err := toml.DecodeFile(f, &c)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
return c
}
func checkPage(url string, pattern string, ch chan<- Result) {
var res Result
res.Url = url
prefetch := time.Now()
client := http.Client{
Timeout: 5 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
if err != nil {
res.Error = err
} else {
patternExists := checkForPattern(string(body), pattern)
if patternExists == true {
} else {
m := fmt.Sprintf("ERROR: %s - Pattern not found: %s", url, pattern)
err := errors.New(m)
res.Error = err
}
}
res.Duration = time.Since(prefetch).Seconds()
ch <- res
}
func main() {
configFile := "config.toml"
for {
c := getConfig(configFile)
loopstart := time.Now()
ch := make(chan Result)
for i := 0; i < len(c.Sites); i++ {
urlToCheck := c.Sites[i].Url
pattern := c.Sites[i].Pattern
go checkPage(urlToCheck, pattern, ch)
}
for i := 0; i < len(c.Sites); i++ {
ret := <-ch
fmt.Printf("%s - %v - %.2fs\n", ret.Url, ret.Error, ret.Duration)
}
fmt.Printf("%.2fs elapsed\n\n", time.Since(loopstart).Seconds())
time.Sleep(5 * time.Second)
}
}