Big commit

This commit is contained in:
Ben Sarmiento
2023-10-24 22:14:04 +02:00
parent 91472334b9
commit 2ce8273779
8 changed files with 105 additions and 71 deletions

View File

@@ -21,34 +21,42 @@ func RetryUntilOk[T any](fn func() (T, error)) T {
}
func canFetchFirstByte(url string) bool {
// Create a new HTTP request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false
}
const maxAttempts = 3
// Set the Range header to request only the first byte
req.Header.Set("Range", "bytes=0-0")
for i := 0; i < maxAttempts; i++ {
// Create a new HTTP request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
continue
}
// Execute the request
resp, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
// Set the Range header to request only the first byte
req.Header.Set("Range", "bytes=0-0")
// If server supports partial content
if resp.StatusCode == http.StatusPartialContent {
buffer := make([]byte, 1)
_, err := resp.Body.Read(buffer)
return err == nil
// Execute the request
resp, err := http.DefaultClient.Do(req)
if err != nil {
time.Sleep(1 * time.Second) // Add a delay before the next retry
continue
}
defer resp.Body.Close()
// If server supports partial content
if resp.StatusCode == http.StatusPartialContent {
buffer := make([]byte, 1)
_, err := resp.Body.Read(buffer)
if err == nil {
return true
}
} else if resp.StatusCode == http.StatusOK {
// If server doesn't support partial content, try reading the first byte and immediately close
buffer := make([]byte, 1)
_, err = resp.Body.Read(buffer)
if err == nil {
return true
}
}
time.Sleep(1 * time.Second) // Add a delay before the next retry
}
if resp.StatusCode != http.StatusOK {
return false
}
// If server doesn't support partial content, try reading the first byte and immediately close
buffer := make([]byte, 1)
_, err = resp.Body.Read(buffer)
resp.Body.Close() // Close immediately after reading
return err == nil
return false
}