Любомир обнови решението на 11.12.2014 16:48 (преди над 3 години)
+package main
+
+import "errors"
+import "net/http"
+import "io/ioutil"
+import "time"
+
+func SeekAndDestroy(callback func(string) bool, chunkedUrlsToCheck chan []string, workersCount int) (target string, err error) {
+ if workersCount < 1 {
+ return "", errors.New("Invalid workers count")
+ }
+ if chunkedUrlsToCheck == nil {
+ return "", errors.New("Uninitialized chanel")
+ }
+
+ items := make(chan string)
+ done := make(chan struct{})
+
+ for c := 0; c < workersCount; c++ {
+ go func() {
+ for {
+ select {
+ case url := <-items:
+ res := http.Client{Timeout: time.Duration(3 * time.Second)}
+ if result, err := res.Get(url); err == nil {
+ content, _ := ioutil.ReadAll(result.Body)
+ result.Body.Close()
+ if callback(string(content)) {
+ target = url
+ for s := 0; s < workersCount; s++ {
+ done <- struct{}{}
+ }
+ }
+ }
+ case <-done:
+ return
+ }
+ }
+ }()
+ }
+
+ for {
+ select {
+ case <-done:
+ return
+ case chunk := <-chunkedUrlsToCheck:
+ for _, url := range chunk {
+ items <- url
+ }
+ case <-time.After(15 * time.Second):
+ return "", errors.New("Timeout")
+ }
+ }
+
+}