forked from Team-Ortix/StatusApp
49 lines
1.1 KiB
Go
49 lines
1.1 KiB
Go
|
package check
|
||
|
|
||
|
import (
|
||
|
"net/http"
|
||
|
"net/http/httptrace"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
//HTTPPing returns the response time to fetch a page.
|
||
|
func HTTPPing(target string) (time.Duration, Result, error) {
|
||
|
var totalTime time.Duration
|
||
|
var err error
|
||
|
successCount := 0
|
||
|
okCount := 0
|
||
|
for i := 0; i < TryCount; i++ {
|
||
|
duration, successful, getErr := timeGet(target)
|
||
|
totalTime += duration
|
||
|
if getErr != nil {
|
||
|
err = getErr
|
||
|
}
|
||
|
if successful {
|
||
|
okCount++
|
||
|
}
|
||
|
successCount++
|
||
|
}
|
||
|
return divide(totalTime, successCount), statusFromSuccessCount(okCount), err
|
||
|
}
|
||
|
|
||
|
func timeGet(url string) (time.Duration, bool, error) {
|
||
|
req, _ := http.NewRequest("GET", url, nil)
|
||
|
|
||
|
var connect time.Time
|
||
|
var duration time.Duration
|
||
|
|
||
|
trace := &httptrace.ClientTrace{
|
||
|
ConnectStart: func(network, addr string) { connect = time.Now() },
|
||
|
GotFirstResponseByte: func() {
|
||
|
duration = time.Since(connect)
|
||
|
},
|
||
|
}
|
||
|
|
||
|
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
|
||
|
res, err := http.DefaultTransport.RoundTrip(req)
|
||
|
if err != nil {
|
||
|
return 0, false, err
|
||
|
}
|
||
|
return duration, res.StatusCode < 400, nil
|
||
|
}
|