This commit is contained in:
Colin 2024-05-21 12:30:07 -04:00
parent 56693b76bc
commit 26522adf6e
9 changed files with 15 additions and 29 deletions

BIN
dist/ttfb-go vendored

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
dist/ttfb-go_linux_arm vendored

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
dist/ttfb-go_static vendored

Binary file not shown.

34
main.go
View File

@ -30,42 +30,28 @@ func MeasureTTFB(url string, cookie string) (int64, int, error) {
// If a cookie is provided, set it in the request header. // If a cookie is provided, set it in the request header.
if cookie != "" { if cookie != "" {
// Clean up and format the cookie properly
cookie = strings.TrimSpace(cookie)
if !strings.Contains(cookie, "=") {
return 0, 0, fmt.Errorf("invalid cookie format")
}
req.Header.Set("Cookie", cookie) req.Header.Set("Cookie", cookie)
} }
// Create a channel to capture the time to first byte // Record the start time.
ttfbChan := make(chan int64)
errorChan := make(chan error)
statusCodeChan := make(chan int)
// Record the start time
start := time.Now() start := time.Now()
go func() { // Perform the request.
// Perform the request
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
errorChan <- err return 0, 0, err
return
} }
defer resp.Body.Close() defer resp.Body.Close()
// Measure the time taken to receive the first byte // Measure the time taken to receive the first byte.
ttfb := time.Since(start).Milliseconds() ttfb := time.Since(start).Milliseconds()
ttfbChan <- ttfb
statusCodeChan <- resp.StatusCode
// Read the body to ensure we handle the response properly return ttfb, resp.StatusCode, nil
_, _ = ioutil.ReadAll(resp.Body)
}()
select {
case ttfb := <-ttfbChan:
statusCode := <-statusCodeChan
return ttfb, statusCode, nil
case err := <-errorChan:
return 0, 0, err
}
} }
func main() { func main() {