Channels
This commit is contained in:
2
channels/Makefile
Normal file
2
channels/Makefile
Normal file
@ -0,0 +1,2 @@
|
||||
run:
|
||||
@go run main.go
|
||||
3
channels/go.mod
Normal file
3
channels/go.mod
Normal file
@ -0,0 +1,3 @@
|
||||
module channelsdemo
|
||||
|
||||
go 1.21.6
|
||||
68
channels/main.go
Normal file
68
channels/main.go
Normal file
@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user