oseda_cli/
net.rs

1use std::{error::Error, process::Command};
2
3/// Checks the status of host url from a GET request
4///
5/// # Arguments
6/// * `host` - the full URL to check -> eg.. `"http://localhost:3000"`
7///
8/// # Returns
9/// * `Ok(StatusCode)` if the request was successfully sent, containing the resulting status code
10/// * `Err` if the request fails to *send*. This is not reflective of the status code
11///
12pub fn get_status(host: &str) -> Result<reqwest::StatusCode, Box<dyn Error>> {
13    let response = reqwest::blocking::get(host)?;
14
15    Ok(response.status())
16}
17
18/// Kills any process listening to a provided port number
19///
20/// # Platform
21/// This function only works on Unix based systems
22///
23/// # Arguments
24/// * `port_num` - the TCP port number to search for and terminate
25///
26/// # Returns
27/// * `Ok(())` if processes were successfully terminated -> even if none were found
28/// * `Err` if `lsof` or `kill` fails, or if output cannot be parsed properly
29pub fn kill_port(port_num: u16) -> Result<(), Box<dyn Error>> {
30    // TIL cargo lets you do # Platform in the doc comments
31
32    let lsof_out = Command::new("lsof")
33        .arg("-t")
34        .arg(format!("-i:{}", port_num))
35        .output()?;
36
37    let procs_on_port = String::from_utf8(lsof_out.stdout)?;
38
39    for pid in procs_on_port.lines() {
40        Command::new("kill").arg(pid).output()?;
41    }
42
43    Ok(())
44}