package main
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
"sync/atomic"
"time"
)
var (
success, fail int64
wg sync.WaitGroup
)
const (
goroutines = 4
duration = 30 * time.Second
)
func main() {
timer := time.NewTimer(duration)
for {
select {
case <-timer.C:
fmt.Println("success", success, "fail", fail)
return
default:
wg.Add(goroutines)
for i := 0; i < goroutines; i++ {
}
wg.Wait()
}
}
}
func hit(url string) {
defer wg.Done()
resp, err := http.Get(url) // error occurs here
if err != nil {
fmt.Println(err)
atomic.AddInt64(&fail, 1)
return
}
_, err = io.Copy(ioutil.Discard, resp.Body)
if err != nil {
fmt.Println(err)
}
err = resp.Body.Close()
if err != nil {
fmt.Println(err)
}
if resp.StatusCode != http.StatusOK {
atomic.AddInt64(&fail, 1)
return
}
atomic.AddInt64(&success, 1)
}