| 1 | // Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved. |
| 2 | // Use of this source code is governed by an MIT license |
| 3 | // that can be found in the LICENSE file. |
| 4 | module http |
| 5 | |
| 6 | import os |
| 7 | |
| 8 | // download_file retrieves a document from the URL `url`, |
| 9 | // and saves it in the output file path `out_file_path`. |
| 10 | pub fn download_file(url string, out_file_path string) ! { |
| 11 | $if debug_http ? { |
| 12 | println('http.download_file url=${url} out_file_path=${out_file_path}') |
| 13 | } |
| 14 | s := get(url) or { return err } |
| 15 | if s.status() != .ok { |
| 16 | return error_with_code(s.body, s.status_code) |
| 17 | } |
| 18 | $if debug_http ? { |
| 19 | println('http.download_file saving ${s.body.len} bytes') |
| 20 | } |
| 21 | os.write_file(out_file_path, s.body)! |
| 22 | } |
| 23 | |
| 24 | pub fn download_file_with_cookies(url string, out_file_path string, cookies map[string]string) ! { |
| 25 | $if debug_http ? { |
| 26 | println('http.download_file url=${url} out_file_path=${out_file_path}') |
| 27 | } |
| 28 | s := fetch(method: .get, url: url, cookies: cookies) or { return err } |
| 29 | if s.status() != .ok { |
| 30 | return error('received http code ${s.status_code}') |
| 31 | } |
| 32 | $if debug_http ? { |
| 33 | println('http.download_file saving ${s.body.len} bytes') |
| 34 | } |
| 35 | os.write_file(out_file_path, s.body)! |
| 36 | } |
| 37 | |