From 5578d70154187eddc4a5fd672533aa9cd44a04e6 Mon Sep 17 00:00:00 2001 From: Eden Kirin Date: Sat, 20 Jan 2024 19:49:42 +0100 Subject: [PATCH] Channels --- channels/Makefile | 2 ++ channels/go.mod | 3 +++ channels/main.go | 68 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) create mode 100644 channels/Makefile create mode 100644 channels/go.mod create mode 100644 channels/main.go diff --git a/channels/Makefile b/channels/Makefile new file mode 100644 index 0000000..860613c --- /dev/null +++ b/channels/Makefile @@ -0,0 +1,2 @@ +run: + @go run main.go \ No newline at end of file diff --git a/channels/go.mod b/channels/go.mod new file mode 100644 index 0000000..ed6b342 --- /dev/null +++ b/channels/go.mod @@ -0,0 +1,3 @@ +module channelsdemo + +go 1.21.6 diff --git a/channels/main.go b/channels/main.go new file mode 100644 index 0000000..68c6904 --- /dev/null +++ b/channels/main.go @@ -0,0 +1,68 @@ +package main + +import ( + "fmt" + "io" + "net/http" + "sync" +) + +var Urls = []string{ + "https://www.index.hr", + "https://www.vecernji.hr", + "https://www.jutarnji.hr", + "https://www.jutarnji.hrxxx/", +} + +func fetchUrl(url string) (*string, error) { + resp, err := http.Get(url) + if err != nil { + return nil, err + } + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + + bodyStr := string(body) + + return &bodyStr, nil +} + +func main() { + var wg sync.WaitGroup + chMessages := make(chan string) + chDone := make(chan bool) + + wg.Add(len(Urls)) + + for _, url := range Urls { + go func(url string) { + defer wg.Done() + + chMessages <- fmt.Sprintf("Fetching %s...", url) + body, err := fetchUrl(url) + if err != nil { + chMessages <- fmt.Sprintf("Error fetching %s. Length: %v", url, err) + } else { + chMessages <- fmt.Sprintf("Done fetching %s. Length: %d", url, len(*body)) + } + }(url) + } + + go func() { + for msg := range chMessages { + fmt.Println(msg) + } + // signal that message reader is done + chDone <- true + }() + + wg.Wait() + + // close messages channel to stop reading from message stream + close(chMessages) + + // wait for chMessages reader to get done + <-chDone +}