Skip to content

Instantly share code, notes, and snippets.

@obutora
Created May 21, 2024 13:02
Show Gist options
  • Save obutora/ab7c415ca107e0ce0818f48fc87e35e6 to your computer and use it in GitHub Desktop.
Save obutora/ab7c415ca107e0ce0818f48fc87e35e6 to your computer and use it in GitHub Desktop.
goroutineを使ったエラーハンドリング
package main
import (
"fmt"
"net/http"
)
// errorとレスポンスをセットにしてラップする構造体
type Result struct {
Error error
Response *http.Response
}
func main() {
// done channelで制御されるgoroutineを作成
checkStatus := func(done <- chan struct{}, urls ...string) <- chan Result {
results := make(chan Result)
go func() {
defer close(results)
for _, url := range urls {
var result Result
resp, err := http.Get(url)
// ラップされた構造体を作成
result = Result{Error: err, Response: resp}
select {
case <- done:
return
case results <- result:
}
}
}()
return results
}
done := make(chan struct{})
defer close(done)
// エラーの数で柔軟なハンドリングを行うための変数
errCount := 0
urls := []string{"http://google.com", "http://badhost", "b", "c"}
for result := range checkStatus(done, urls...) {
if result.Error != nil {
errCount++
// エラーが2回以上発生したら終了
if errCount > 2 {
fmt.Println("Too many errors")
break
}
fmt.Printf("error %v :%v\n", errCount, result.Error)
continue
}
fmt.Println("Response:", result.Response.Status)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment