go-pingbot/ping/ping.go

52 lines
788 B
Go
Raw Permalink Normal View History

2021-09-08 20:18:35 +00:00
package ping
2021-07-11 21:19:37 +00:00
import (
"context"
2021-07-11 21:19:37 +00:00
"net/http"
"time"
2021-07-11 21:19:37 +00:00
2021-08-12 19:26:54 +00:00
"github.com/MedzikUser/go-utils/common"
2021-11-10 13:38:54 +00:00
"github.com/medzikuser/go-pingbot/config"
2021-07-11 21:19:37 +00:00
)
2021-08-29 10:14:35 +00:00
func ping() int {
2021-09-05 11:20:19 +00:00
Cache()
2021-09-05 11:20:19 +00:00
for _, url := range CacheURL {
go loop(url)
2021-07-11 21:19:37 +00:00
}
2021-08-29 10:14:35 +00:00
2021-09-05 11:20:19 +00:00
return len(CacheURL)
2021-07-11 21:19:37 +00:00
}
func loop(url string) {
// Timeout 1 minute
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
2021-11-07 19:19:06 +00:00
if err != nil {
common.Log.Error("new http request", err)
2021-07-29 18:51:15 +00:00
Status.Error++
return
}
2021-10-15 19:15:29 +00:00
req.Header.Set("User-Agent", config.UserAgent)
client := http.DefaultClient
r, err := client.Do(req)
if err != nil {
2021-07-29 18:51:15 +00:00
Status.Error++
2021-07-11 21:19:37 +00:00
return
}
if r.StatusCode >= 200 && r.StatusCode < 400 {
2021-07-29 18:51:15 +00:00
Status.Success++
2021-07-11 21:19:37 +00:00
} else {
2021-07-29 18:51:15 +00:00
Status.Error++
2021-07-11 21:19:37 +00:00
}
}