Skip to content

Instantly share code, notes, and snippets.

@drtaka
Created January 31, 2020 04:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drtaka/682ddead073d379074f806a1a857989e to your computer and use it in GitHub Desktop.
Save drtaka/682ddead073d379074f806a1a857989e to your computer and use it in GitHub Desktop.
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