Created
January 31, 2020 04:51
-
-
Save drtaka/682ddead073d379074f806a1a857989e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"net/http" | |
"fmt" | |
"time" | |
) | |
func main() { | |
type Result struct { | |
Error error | |
Response *http.Response | |
} | |
checkStatus := func(done <-chan struct{}, urls ...string) <-chan Result { | |
results := make(chan Result) | |
go func() { | |
defer close(results) | |
var i int | |
for _, url := range urls { | |
var result Result | |
resp, err := http.Get(url) | |
result = Result{Error: err, Response: resp} | |
select { | |
case <-done: | |
fmt.Printf("%d: got done channel.\n", i) | |
return | |
case results <- result: | |
fmt.Printf("%d: got result.\n", i) | |
} | |
i++ | |
} | |
fmt.Println("Completed go routine.") | |
}() | |
return results | |
} | |
done := make(chan struct{}) | |
defer close(done) | |
defer func() { | |
time.Sleep(3 * time.Second) | |
fmt.Println("Done finally") | |
}() | |
errCounter := 0 | |
urls := []string{"a", "https://www.google.com", "https://badhost", "b", "c", "d"} | |
//urls := []string{"a", "https://www.google.com", "https://www.yahoo.co.jp"} | |
for result := range checkStatus(done, urls...) { | |
if result.Error != nil { | |
fmt.Printf("Error: %s\n", result.Error) | |
errCounter += 1 | |
if errCounter >= 3 { | |
fmt.Println("too many errors, breaking!") | |
//close(done) | |
break | |
} | |
continue | |
} | |
fmt.Printf("Reseponse: %v\n", result.Response.Status) | |
} | |
fmt.Println("done") | |
time.Sleep(5 * time.Second) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment