diff --git a/cmd/newsletter/main.go b/cmd/newsletter/main.go index 1eb1b74..2ceb886 100644 --- a/cmd/newsletter/main.go +++ b/cmd/newsletter/main.go @@ -3,8 +3,82 @@ package main import ( "fmt" + "log/slog" + "os" + "os/signal" + "syscall" + + "github.com/perebaj/newsletter" ) +type Config struct { + LogLevel string + LogType string +} + func main() { - fmt.Println("Hello, World!") + + cfg := Config{ + LogLevel: "INFO", + LogType: "json", + } + + signalCh := make(chan os.Signal, 1) + signal.Notify(signalCh, os.Interrupt, syscall.SIGINT, syscall.SIGTERM) + + if err := setUpLog(cfg); err != nil { + slog.Error("error setting up log", "error", err) + signalCh <- syscall.SIGTERM + } + + sSlice := []string{"http://www.google.com", "www.facebook.com", "www.x.com"} + jobs := make(chan string, len(sSlice)) + result := make(chan string, len(sSlice)) + for _, s := range sSlice { + jobs <- s + } + + go newsletter.Worker(jobs, result, newsletter.GetReferences) + + for i := 0; i < len(sSlice); i++ { + r := <-result + if r != "" { + slog.Info(r) + } + } + + <-signalCh +} + +// setUpLog initialize the logger. +func setUpLog(cfg Config) error { + var level slog.Level + switch cfg.LogLevel { + case "INFO": + level = slog.LevelInfo + case "DEBUG": + level = slog.LevelDebug + case "WARN": + level = slog.LevelWarn + case "ERROR": + level = slog.LevelError + default: + return fmt.Errorf("invalid log level: %s", cfg.LogLevel) + } + + var logger *slog.Logger + if cfg.LogType == "json" { + logger = slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ + Level: level, + })) + } else if cfg.LogType == "text" { + logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ + Level: level, + })) + } else { + return fmt.Errorf("invalid log type: %s", cfg.LogType) + } + + slog.SetDefault(logger) + return nil } diff --git a/cmd/newsletter/newsletter b/cmd/newsletter/newsletter index 3f94e3b..ac7704d 100755 Binary files a/cmd/newsletter/newsletter and b/cmd/newsletter/newsletter differ diff --git a/scrape.go b/scrape.go index 11818ca..80e7dcb 100644 --- a/scrape.go +++ b/scrape.go @@ -40,7 +40,7 @@ func Worker(jobs <-chan string, result chan<- string, f func(string) (string, er for j := range jobs { content, err := f(j) if err != nil { - fmt.Printf("error getting reference %s: %v", j, err) + slog.Error(fmt.Sprintf("error getting reference: %s", j), "error", err) } result <- content }