-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
145 lines (116 loc) · 2.41 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
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
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
const monitoringNumber = 3
const monitoringDelay = 5
func main() {
TerminalIntroduction()
for {
menuOptions()
command, err := commandInput()
if err != nil {
log.Printf("Invalid command - %v", err)
}
switch command {
case 1:
startMonitor()
case 2:
showLog()
case 0:
fmt.Println("Finished.")
os.Exit(0)
default:
fmt.Println("Invalid command")
os.Exit(-1)
}
}
}
func TerminalIntroduction() {
name := "Luan Sapelli"
version := 1.0
fmt.Println("\n Hello", name)
fmt.Println("Program Version:", version)
}
func menuOptions() {
fmt.Println("1 - Start Monitor")
fmt.Println("2 - Show Logs")
fmt.Println("0 - Exit")
fmt.Println("")
}
func commandInput() (int, error) {
var commandInput int
_, err := fmt.Scan(&commandInput)
if err != nil {
return 0, err
}
return commandInput, nil
}
func startMonitor() {
fmt.Println("Monitoring...")
sites := siteArchive()
for i := 0; i < monitoringNumber; i++ {
for i, site := range sites {
fmt.Println("Monitoring site", i, site)
siteStatus(site)
}
time.Sleep(monitoringDelay * time.Second)
fmt.Println("")
}
fmt.Println("")
}
func siteStatus(site string) {
resp, err := http.Get(site)
if err != nil {
fmt.Println("Error: ", err)
}
if resp.StatusCode == 200 {
fmt.Println("Site:", site, "is online. Status code: ", resp.StatusCode)
writeLog(site, true)
} else {
fmt.Println("Site:", site, "is offline. Status Code: ", resp.StatusCode)
writeLog(site, false)
}
}
func siteArchive() []string {
var sites []string
archive, err := os.Open("sites.txt")
if err != nil {
fmt.Println("Error: ", err)
}
reader := bufio.NewReader(archive)
for {
line, err := reader.ReadString('\n')
line = strings.TrimSpace(line)
sites = append(sites, line)
if err == io.EOF {
break
}
}
_ = archive.Close()
return sites
}
func writeLog(site string, status bool) {
archive, err := os.OpenFile("log.txt", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Printf("Error to open file - %v", err)
}
_, err = archive.WriteString(time.Now().Format("Mon 02/01/2006 15:04:05") + " - " + site + " - online:" + strconv.FormatBool(status) + "\n")
_ = archive.Close()
}
func showLog() {
archive, err := ioutil.ReadFile("log.txt")
if err != nil {
fmt.Println(err)
}
fmt.Println(string(archive))
}