lib_ngrok/
lib.rs

1//! Easily download and run an ngrok binary.
2//!
3//! # Examples
4//!
5//! ```rust
6//! use lib_ngrok::download;
7//!
8//! async fn download() -> Result<(), anyhow::Error> {
9//!     let ngrok_path = &Path::new("ngrok");
10//!     download::bin(ngrok_path).await?;
11//! }
12//! ```
13
14use std::{
15    ffi::OsStr,
16    io,
17    path::Path,
18    process::{Command, ExitStatus},
19};
20use thiserror::Error;
21
22pub mod url;
23
24#[cfg(feature = "download")]
25pub mod download;
26
27/// Errors that can occur when running an ngrok binary.
28#[derive(Error, Debug)]
29pub enum RunError {
30    #[error("could not run ngrok. status: {0}")]
31    CouldNotRun(ExitStatus),
32    #[error("could not find ngrok binary")]
33    CouldNotFindBinary,
34    #[error("io")]
35    IO(#[from] io::Error),
36}
37
38/// Runs an ngrok binary with an authentication token.
39///
40/// Make sure that the bin is an ngrok path.
41///
42/// The `auth_token` parameter sets an enviornemnt variable `NGROK_AUTHTOKEN` to what you specify.
43pub fn run<T: AsRef<OsStr>>(bin: &Path, auth_token: &str, args: &[T]) -> Result<(), RunError> {
44    let mut child = Command::new(bin)
45        .env("NGROK_AUTHTOKEN", auth_token)
46        .args(args)
47        .spawn()?;
48
49    let status = child.wait()?;
50
51    if !status.success() {
52        return Err(RunError::CouldNotRun(status));
53    }
54
55    Ok(())
56}