@@ -11,33 +11,29 @@ using namespace hv;
1111typedef std::function<void (size_t received_bytes, size_t total_bytes)> wget_progress_cb;
1212
1313static int wget (const char * url, const char * filepath, wget_progress_cb progress_cb = NULL ) {
14- HFile file;
15- if (file.open (filepath, " wb" ) != 0 ) {
16- fprintf (stderr, " Failed to open file %s\n " , filepath);
17- return -20 ;
18- }
19- printf (" Save file to %s ...\n " , filepath);
20-
14+ int ret = 0 ;
2115 HttpClient cli;
2216 HttpRequest req;
23- req.url = url;
2417 HttpResponse resp;
2518
2619 // HEAD
2720 req.method = HTTP_HEAD;
28- int ret = cli.send (&req, &resp);
21+ req.url = url;
22+ ret = cli.send (&req, &resp);
2923 if (ret != 0 ) {
3024 fprintf (stderr, " request error: %d\n " , ret);
31- return - 1 ;
25+ return ret ;
3226 }
3327 printd (" %s" , resp.Dump (true , false ).c_str ());
3428 if (resp.status_code == HTTP_STATUS_NOT_FOUND) {
3529 fprintf (stderr, " 404 Not Found\n " );
36- return - 1 ;
30+ return 404 ;
3731 }
3832
33+ // use Range?
3934 bool use_range = false ;
4035 int range_bytes = 1 << 20 ; // 1M
36+ long from = 0 , to = 0 ;
4137 std::string accept_ranges = resp.GetHeader (" Accept-Ranges" );
4238 size_t content_length = hv::from_string<size_t >(resp.GetHeader (" Content-Length" ));
4339 // use Range if server accept_ranges and content_length > 1M
@@ -47,6 +43,15 @@ static int wget(const char* url, const char* filepath, wget_progress_cb progress
4743 use_range = true ;
4844 }
4945
46+ // open file
47+ HFile file;
48+ ret = file.open (filepath, " wb" );
49+ if (ret != 0 ) {
50+ fprintf (stderr, " Failed to open file %s\n " , filepath);
51+ return ret;
52+ }
53+ printf (" Save file to %s ...\n " , filepath);
54+
5055 // GET
5156 req.method = HTTP_GET;
5257 req.timeout = 3600 ; // 1h
@@ -71,13 +76,12 @@ static int wget(const char* url, const char* filepath, wget_progress_cb progress
7176 ret = cli.send (&req, &resp);
7277 if (ret != 0 ) {
7378 fprintf (stderr, " request error: %d\n " , ret);
74- return - 1 ;
79+ goto error ;
7580 }
7681 return 0 ;
7782 }
7883
7984 // Range: bytes=from-to
80- long from = 0 , to = 0 ;
8185 while (from < content_length) {
8286 to = from + range_bytes - 1 ;
8387 if (to >= content_length) to = content_length - 1 ;
@@ -86,7 +90,7 @@ static int wget(const char* url, const char* filepath, wget_progress_cb progress
8690 ret = cli.send (&req, &resp);
8791 if (ret != 0 ) {
8892 fprintf (stderr, " request error: %d\n " , ret);
89- return - 1 ;
93+ goto error ;
9094 }
9195 printd (" %s" , resp.Dump (true , false ).c_str ());
9296 file.write (resp.body .data (), resp.body .size ());
@@ -98,6 +102,10 @@ static int wget(const char* url, const char* filepath, wget_progress_cb progress
98102 }
99103
100104 return 0 ;
105+ error:
106+ file.close ();
107+ remove (filepath);
108+ return ret;
101109}
102110
103111int main (int argc, char ** argv) {
0 commit comments