Interfaces assignment2 and channels

This commit is contained in:
Johannes Rothe 2022-02-14 22:34:03 +01:00
parent a00a517606
commit 60fa2f4ef7
6 changed files with 69 additions and 0 deletions

3
channels/go.mod Normal file
View File

@ -0,0 +1,3 @@
module channels
go 1.17

40
channels/main.go Normal file
View File

@ -0,0 +1,40 @@
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
urls := []string{
"https://google.com",
"https://facebook.com",
"https://golang.org",
"https://johannes-rothe.de",
"https://amazon.com",
}
c := make(chan string)
for _, url := range urls {
go checkURL(url, c)
}
for url := range c { // wait for the channel to return a value, then assign it to l
go func(url string) {
time.Sleep(2 * time.Second)
checkURL(url, c)
}(url)
//go checkURL(url, c)
//fmt.Println(<-c) // value through c is a blocking call
}
}
func checkURL(url string, c chan string) {
_, err := http.Get(url)
if err != nil {
fmt.Printf("%s might be down!\n", url)
c <- url
return
}
fmt.Printf("%s is up!\n", url)
c <- url
}

View File

@ -0,0 +1,3 @@
module interfaces_assignment2
go 1.17

Binary file not shown.

View File

@ -0,0 +1,22 @@
package main
import (
"fmt"
"io"
"log"
"os"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("No filename given!\n Usage: %s <filename>\n", os.Args[0])
os.Exit(1)
}
filename := os.Args[1]
file, err := os.Open(filename)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
io.Copy(os.Stdout, file)
}

View File

@ -0,0 +1 @@
Hello World!