Skip to content

Commit

Permalink
✨ set up main
Browse files Browse the repository at this point in the history
  • Loading branch information
perebaj committed Jan 18, 2024
1 parent 4cdf2f9 commit 694f826
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 2 deletions.
76 changes: 75 additions & 1 deletion cmd/newsletter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Binary file modified cmd/newsletter/newsletter
Binary file not shown.
2 changes: 1 addition & 1 deletion scrape.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down

0 comments on commit 694f826

Please sign in to comment.