Skip to content

Commit

Permalink
chore: adjust switch_port name & add docs
Browse files Browse the repository at this point in the history
  • Loading branch information
lomirus committed Dec 20, 2023
1 parent 405f973 commit 3e1c550
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 6 deletions.
7 changes: 5 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,19 +34,22 @@ static TX: OnceCell<broadcast::Sender<()>> = OnceCell::const_new();
/// listen("127.0.0.1", 8080, "./", true).await.unwrap();
/// }
/// ```
/// When the `port` you specified is unavailable and `switch_port`
/// is set to `true`, live-server will try to switch to `8081`
/// and then `8082` until it finds an available port.
pub async fn listen<R: Into<PathBuf>>(
host: &str,
port: u16,
root: R,
try_to_switch_to_an_available_port: bool,
switch_port: bool,
) -> Result<(), Box<dyn Error>> {
HOST.set(host.to_string()).unwrap();
ROOT.set(root.into()).unwrap();
let (tx, _) = broadcast::channel(16);
TX.set(tx).unwrap();

let watcher_future = tokio::spawn(watcher::watch());
let server_future = tokio::spawn(server::serve(port, try_to_switch_to_an_available_port));
let server_future = tokio::spawn(server::serve(port, switch_port));

let (_, server_result) = tokio::try_join!(watcher_future, server_future)?;
server_result?;
Expand Down
8 changes: 4 additions & 4 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ use tokio::net::TcpListener;

use crate::{HOST, PORT, ROOT, TX};

pub async fn serve(port: u16, switch_to_available_ports: bool) -> Result<(), String> {
let listener = create_listener(port, switch_to_available_ports).await?;
pub async fn serve(port: u16, switch_port: bool) -> Result<(), String> {
let listener = create_listener(port, switch_port).await?;
let app = create_server();
axum::serve(listener, app).await.unwrap();

Expand All @@ -23,7 +23,7 @@ pub async fn serve(port: u16, switch_to_available_ports: bool) -> Result<(), Str

async fn create_listener(
port: u16,
switch_to_available_ports: bool,
switch_port: bool,
) -> Result<TcpListener, String> {
let host = HOST.get().unwrap();
let mut port = port;
Expand All @@ -37,7 +37,7 @@ async fn create_listener(
}
Err(err) => {
if let std::io::ErrorKind::AddrInUse = err.kind() {
if switch_to_available_ports {
if switch_port {
log::warn!("Port {} is already in use", port);
port += 1;
} else {
Expand Down

0 comments on commit 3e1c550

Please sign in to comment.