Created
May 23, 2024 03:17
-
-
Save Lua12138/74638b80d43416b648f0ee5d846ddc73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"fmt" | |
"io" | |
"net/http" | |
"os" | |
) | |
func Download(url string, filepath string) error { | |
offset := int64(0) | |
info, err := os.Stat(filepath) | |
if err == nil { | |
// continue to donwload | |
offset = info.Size() | |
} | |
fs, err := os.OpenFile(filepath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644) | |
if err != nil { | |
// failre to open/create file | |
return err | |
} | |
defer fs.Close() | |
// check file size from remote | |
request, err := http.NewRequest("HEAD", url, nil) | |
if err != nil { | |
return err | |
} | |
response, err := http.DefaultClient.Do(request) | |
if err != nil { | |
return err | |
} | |
if response.StatusCode < 200 || response.StatusCode > 299 { | |
return fmt.Errorf("request HEAD with status code %d", response.StatusCode) | |
} | |
totalSize := response.ContentLength | |
response.Body.Close() | |
if totalSize <= offset { | |
return nil | |
} | |
request, err = http.NewRequest("GET", url, nil) | |
if err != nil { | |
return err | |
} | |
request.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset)) | |
response, err = http.DefaultClient.Do(request) | |
if err != nil { | |
return err | |
} | |
if response.StatusCode < 200 || response.StatusCode > 299 { | |
return fmt.Errorf("request with status code %d", response.StatusCode) | |
} | |
defer response.Body.Close() | |
_, err = fs.Seek(offset, io.SeekStart) | |
if err != nil { | |
return err | |
} | |
_, err = io.Copy(fs, response.Body) | |
return err | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment