@@ -31,13 +31,7 @@ type downloadRequest struct {
3131// It writes to the destination file as it downloads it, without
3232// loading the entire file into memory.
3333func downloadFile (downloadRequest * downloadRequest ) error {
34- targetFile , err := os .Create (downloadRequest .TargetPath )
35- if err != nil {
36- return fmt .Errorf ("creating file: %w" , err )
37- }
38- defer func () {
39- _ = targetFile .Close ()
40- }()
34+ stat , _ := os .Stat (downloadRequest .TargetPath )
4135
4236 exp := getExponentialBackoff (3 )
4337
@@ -47,31 +41,49 @@ func downloadFile(downloadRequest *downloadRequest) error {
4741 if err != nil {
4842 return fmt .Errorf ("creating request: %w" , err )
4943 }
50- resp , err := http .DefaultClient .Do (req )
44+ // if the target file already exists, add the If-Modified-Since header
45+ if stat != nil {
46+ req .Header .Add ("If-Modified-Since" , stat .ModTime ().Format (http .TimeFormat ))
47+ }
48+
49+ resp , err := http .DefaultClient .Do (req ) //nolint:bodyclose // we do close this outside of the function
5150 if err != nil {
5251 retryCount ++
5352 return fmt .Errorf ("downloading file %s: %w" , downloadRequest .URL , err )
5453 }
5554 defer func () {
5655 _ = resp .Body .Close ()
5756 }()
57+
58+ if resp .StatusCode == http .StatusNotModified {
59+ return nil
60+ }
61+
62+ targetFile , err := os .Create (downloadRequest .TargetPath )
63+ if err != nil {
64+ return fmt .Errorf ("creating file: %w" , err )
65+ }
66+ defer func () {
67+ _ = targetFile .Close ()
68+ }()
69+
5870 _ , err = io .Copy (targetFile , resp .Body )
5971 if err != nil {
6072 // try to drain the body before returning to ensure the connection can be reused
6173 _ , _ = io .Copy (io .Discard , resp .Body )
6274 return fmt .Errorf ("writing file %s: %w" , targetFile .Name (), err )
6375 }
6476
77+ _ = os .Chmod (targetFile .Name (), 0666 )
78+
6579 return nil
6680 }
6781
68- err = backoff .Retry (download , exp )
82+ err : = backoff .Retry (download , exp )
6983 if err != nil {
7084 return err
7185 }
7286
73- _ = os .Chmod (targetFile .Name (), 0666 )
74-
7587 return nil
7688}
7789
0 commit comments