diff --git a/wbmalert.go b/wbmalert.go index e948adc..e41d9a2 100644 --- a/wbmalert.go +++ b/wbmalert.go @@ -1,8 +1,9 @@ package main import ( + "fmt" "io" - "log" + "log/slog" "net/http" "strings" "sync" @@ -66,26 +67,30 @@ func createInitialSnapshot(website *website, wg *sync.WaitGroup) { content, err := getWebsiteAsString(website) if err == nil { website.Snapshot = content - log.Println("Created initial snapshot for " + website.Name) + slog.Info("Created initial snapshot for", "website", website.Name) } else { - log.Println(err) + slog.Error("Can't create snapshot for", "website", website.Name, "error", err) } defer wg.Done() } func getWebsiteAsString(website *website) (string, error) { request, err := http.NewRequest(http.MethodGet, website.Url, nil) + errorText := fmt.Sprintf("Error fetching %s", website.Name) if err != nil { - return "Error", err + return errorText, err } resp, err := client.Do(request) if err != nil { - return "Error", err + return errorText, err + } + if resp.StatusCode >= 400 { + return errorText, fmt.Errorf("http status code error occured : %d", resp.StatusCode) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { - return "Error", err + return errorText, err } content := string(body[:]) content = removeByRegexp(content, website.RegexpRemove) @@ -102,22 +107,22 @@ func checkWebsite(website *website, wg *sync.WaitGroup) { printContentChangeMsg(website) playSound() } else { - log.Println("No changes for " + website.Name) + slog.Info("No changes for", "website", website.Name) } } else { - log.Println(err) + slog.Error("website", website.Name, "error", err) } defer wg.Done() } func printContentChangeMsg(website *website) { - log.Println("========= " + website.Name + " =========") - log.Println("Content changed: " + website.Url) - log.Println("====================" + strings.Repeat("=", len(website.Name))) + slog.Info("========= " + website.Name + " =========") + slog.Info("Content changed: " + website.Url) + slog.Info("====================" + strings.Repeat("=", len(website.Name))) } func goToSleep() { - log.Printf("Going to sleep for %d seconds", interval) + slog.Info("Going to sleep for", "seconds", interval) time.Sleep(time.Duration(interval) * time.Second) } diff --git a/wbmalert_test.go b/wbmalert_test.go index 83937da..bd5e4a7 100644 --- a/wbmalert_test.go +++ b/wbmalert_test.go @@ -20,7 +20,8 @@ func (m *mockClient) Do(req *http.Request) (*http.Response, error) { reader := strings.NewReader(HTTP_GET_BODY) readCloser := io.NopCloser(reader) response := http.Response{ - Body: readCloser, + Body: readCloser, + StatusCode: 200, } return &response, nil }