Skip to main content

Proxy

Struct Proxy 

Source
pub struct Proxy { /* private fields */ }
Expand description

HTTP Proxy server that can be embedded into other applications

This struct encapsulates the proxy state and allows programmatic control over the proxy lifecycle. Configuration is stored in an Arc<RwLock<Config>> so it can be hot-reloaded at runtime (e.g. via the API server).

§Example

use tiny_proxy::{Config, Proxy};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let config = Config::from_file("file.caddy")?;
    let proxy = Proxy::new(config);
    proxy.start("127.0.0.1:8080").await?;
    Ok(())
}

§Hot-reload Example

use tiny_proxy::{Config, Proxy};
use std::sync::Arc;
use tokio::sync::RwLock;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let config = Config::from_file("config.caddy")?;
    let proxy = Proxy::new(config);

    // Get a handle to the shared config for hot-reload
    let config_handle = proxy.shared_config();

    // Spawn proxy in background
    let handle = tokio::spawn(async move {
        if let Err(e) = proxy.start("127.0.0.1:8080").await {
            eprintln!("Proxy error: {}", e);
        }
    });

    // Later, update config at runtime
    let new_config = Config::from_file("updated-config.caddy")?;
    {
        let mut guard = config_handle.write().await;
        *guard = new_config;
    }

    handle.await?;
    Ok(())
}

Implementations§

Source§

impl Proxy

Source

pub fn new(config: Config) -> Self

Create a new proxy instance with the given configuration

The configuration is internally wrapped in Arc<RwLock<Config>> so it can be shared with an API server for hot-reload.

§Arguments
  • config - Configuration loaded from file or constructed programmatically
§Returns

A new Proxy instance ready to be started

Source

pub fn from_shared(config: Arc<RwLock<Config>>) -> Self

Create a new proxy instance from an already shared configuration

Use this when you already have an Arc<RwLock<Config>> that is shared with an API server or other component.

§Arguments
  • config - Shared configuration wrapped in Arc<RwLock<Config>>
Source

pub async fn start(&self, addr: &str) -> Result<()>

Start the proxy server on the specified address

This method blocks indefinitely, handling incoming connections. To run the proxy in the background, spawn it in a tokio task.

Starts a single listener on addr. If matching sites use TLS, an HTTPS listener is started; otherwise plain HTTP. Does not start HTTP→HTTPS redirect servers — use Self::start_all for auto-detect multi-listener mode.

§Arguments
  • addr - Address to listen on (e.g., “127.0.0.1:8080” or “0.0.0.0:8443”)
§Example
proxy.start("127.0.0.1:8080").await?;
Source

pub async fn start_with_addr(&self, addr: SocketAddr) -> Result<()>

Start the proxy server with a parsed SocketAddr

Same as Self::start: one listener on addr, HTTPS or HTTP depending on site TLS config. No automatic HTTP→HTTPS redirect — see Self::start_all.

§Arguments
  • addr - Parsed SocketAddr to listen on
Source

pub async fn start_all(&self) -> Result<()>

Start all listeners defined in the configuration (auto-detect mode).

Scans the config for all unique listen addresses and starts a listener for each. TLS sites get HTTPS listeners with SNI; non-TLS sites get HTTP.

For each distinct TLS port, also starts an HTTP→HTTPS redirect listener: redirect_port = tls_port - 443 + 80 (e.g. 443→80, 8443→8080). Redirect bind is best-effort: if the redirect port is in use, HTTPS still works.

Unlike Self::start / Self::start_with_addr, this method spawns multiple listeners and redirect servers. Use this when the config defines several site addresses (CLI without --addr).

This method blocks until all listener tasks finish (typically forever).

§Example
proxy.start_all().await?;
Source

pub fn shared_config(&self) -> Arc<RwLock<Config>>

Get a reference to the shared configuration handle

This returns a clone of the Arc<RwLock<Config>>, allowing external code (e.g. an API server) to read and update the configuration at runtime.

§Returns

A cloned Arc<RwLock<Config>>

Source

pub async fn config_snapshot(&self) -> Config

Get a snapshot of the current configuration

Reads the current configuration and returns an owned clone. This is useful for inspecting config without holding a lock.

§Returns

A cloned Config

Source

pub fn max_concurrency(&self) -> usize

Get current concurrency limit

§Returns

Current maximum number of concurrent connections

Source

pub fn set_max_concurrency(&mut self, max: usize)

Update concurrency limit at runtime

§Arguments
  • max - New maximum number of concurrent connections
§Note

This updates the semaphore immediately. New connections will use the new limit, but existing connections are not affected.

Source

pub async fn update_config(&self, config: Config)

Update the configuration at runtime (hot-reload)

Atomically replaces routing configuration. New connections use the updated config immediately; in-flight connections keep their original snapshot.

TLS certificates are loaded when a listener starts. This method updates site routing and directives only — not cert/key files or TlsAcceptor. Restart the proxy (or TLS listener) to pick up new certificates.

§Arguments
  • config - New configuration to use

Auto Trait Implementations§

§

impl Freeze for Proxy

§

impl !RefUnwindSafe for Proxy

§

impl Send for Proxy

§

impl Sync for Proxy

§

impl Unpin for Proxy

§

impl UnsafeUnpin for Proxy

§

impl !UnwindSafe for Proxy

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,