-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathurl_metrics_calculator.go
81 lines (73 loc) · 1.99 KB
/
url_metrics_calculator.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
package metrics
import (
"io"
"log"
"net/http"
"regexp"
"time"
"websites_metrics/config"
"websites_metrics/models"
"websites_metrics/repository"
"websites_metrics/scheduler"
)
type URLMetricsCalculator struct {
Repo repository.IMetricsRepository
IScheduler scheduler.IScheduler
}
func (u *URLMetricsCalculator) RunMetricsCalculations(cfg config.URLsConfig) {
for _, urlConfig := range cfg.URLs {
urlConfig := urlConfig
_, err := u.IScheduler.AddFunc(urlConfig.Interval, func() {
metrics, err := u.CalculateMetrics(models.URLConfig{
URL: urlConfig.URL,
Regex: urlConfig.Regex,
})
if err != nil {
log.Printf("error checking URL %s: %v", urlConfig.URL, err)
return
}
log.Printf("URL Metrics: %s %s %f %d %t", metrics.URL, metrics.Timestamp, metrics.ResponseTime, metrics.StatusCode, metrics.RegexMatch)
err = u.Repo.Save(metrics)
if err != nil {
log.Printf("error saving metrics for URL %s: %v", urlConfig.URL, err)
}
})
if err != nil {
log.Printf("error scheduling URL check for %s: %v", urlConfig.URL, err)
}
}
}
func (u *URLMetricsCalculator) CalculateMetrics(urlConfig models.URLConfig) (models.Metric, error) {
start := time.Now()
resp, err := http.Get(urlConfig.URL)
if err != nil {
return models.Metric{}, err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Fatalf("failed to close connection: %v", err)
}
}(resp.Body)
responseTime := time.Since(start).Seconds()
regexMatch := false
if urlConfig.Regex != "" {
bodyBytes, err := io.ReadAll(resp.Body)
if err != nil {
return models.Metric{}, err
}
match, err := regexp.Match(urlConfig.Regex, bodyBytes)
if err != nil {
return models.Metric{}, err
}
regexMatch = match
}
return models.Metric{
URL: urlConfig.URL,
Timestamp: time.Now().Format(time.RFC3339),
ResponseTime: responseTime,
StatusCode: resp.StatusCode,
RegexMatch: regexMatch,
}, nil
}
var _ IURLMetricsCalculator = (*URLMetricsCalculator)(nil)