concurrency
This commit is contained in:
parent
0586ce15a0
commit
06dcef8884
25
concurrency/websitechecker.go
Normal file
25
concurrency/websitechecker.go
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
package concurrency
|
||||||
|
|
||||||
|
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++ {
|
||||||
|
r := <-resultChannel
|
||||||
|
results[r.string] = r.bool
|
||||||
|
}
|
||||||
|
|
||||||
|
return results
|
||||||
|
}
|
47
concurrency/websitechecker_test.go
Normal file
47
concurrency/websitechecker_test.go
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
package concurrency
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func mockWebsiteChecker(url string) bool {
|
||||||
|
return url != "waat://furhurterwe.geds"
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCheckWebsites(t *testing.T) {
|
||||||
|
websites := []string{
|
||||||
|
"http://google.com",
|
||||||
|
"http://blog.gypsydave5.com",
|
||||||
|
"waat://furhurterwe.geds",
|
||||||
|
}
|
||||||
|
|
||||||
|
want := map[string]bool{
|
||||||
|
"http://google.com": true,
|
||||||
|
"http://blog.gypsydave5.com": true,
|
||||||
|
"waat://furhurterwe.geds": false,
|
||||||
|
}
|
||||||
|
|
||||||
|
got := CheckWebsites(mockWebsiteChecker, websites)
|
||||||
|
|
||||||
|
if !reflect.DeepEqual(want, got) {
|
||||||
|
t.Fatalf("wanted %v, got %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func slowStubWesiteChecker(_ string) bool {
|
||||||
|
time.Sleep(20 * time.Millisecond)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkCheckWebsites(b *testing.B) {
|
||||||
|
urls := make([]string, 100)
|
||||||
|
for i := 0; i < len(urls); i++ {
|
||||||
|
urls[i] = "a url"
|
||||||
|
}
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
CheckWebsites(slowStubWesiteChecker, urls)
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user