diff options
| author | mo khan <mo.khan@gmail.com> | 2019-12-08 12:51:18 -0700 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2019-12-08 12:51:18 -0700 |
| commit | 4748519fd9cb750de0d1dd22907e4b9af6fb81c2 (patch) | |
| tree | 60cfce864e22e460e4578853a244442e194efdb3 | |
| parent | e67ebfe8bfca02403bffa9399043220e64323dca (diff) | |
learn about go routines
| -rw-r--r-- | check_websites.go | 25 | ||||
| -rw-r--r-- | check_websites_test.go | 31 |
2 files changed, 56 insertions, 0 deletions
diff --git a/check_websites.go b/check_websites.go new file mode 100644 index 0000000..ad7b0e5 --- /dev/null +++ b/check_websites.go @@ -0,0 +1,25 @@ +package main + +type WebsiteChecker func(string) bool +type result struct { + string + bool +} + +func CheckWebsites(wc WebsiteChecker, urls []string) map[string]bool { + results := make(map[string]bool) + resultChannel := make(chan result) + + for _, url := range urls { + go func(u string) { + resultChannel <- result{u, wc(u)} + }(url) + } + + for i := 0; i < len(urls); i++ { + result := <-resultChannel + results[result.string] = result.bool + } + + return results +} diff --git a/check_websites_test.go b/check_websites_test.go new file mode 100644 index 0000000..b8d4315 --- /dev/null +++ b/check_websites_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "reflect" + "testing" +) + +func mockWebsiteChecker(url string) bool { + if url == "https://www.example.com" { + return false + } + return true +} + +func TestCheckWebsites(t *testing.T) { + websites := []string{ + "https://www.google.com", + "https://www.example.com", + } + + want := map[string]bool{ + "https://www.google.com": true, + "https://www.example.com": false, + } + + got := CheckWebsites(mockWebsiteChecker, websites) + + if !reflect.DeepEqual(want, got) { + t.Fatalf("Wanted %v got %v", want, got) + } +} |
