leotaku / tower-livereload

Tower middleware to automatically reload your web browser during development
Apache License 2.0
59 stars 5 forks source link

Implement configurable request and response predicates #3

Closed leotaku closed 1 year ago

leotaku commented 1 year ago

Also, this necessitates a non backwards-compatible change within the LiveReload initializers. This should be fine and also allows for the removal of some duplicate code.

Here is an example of how one could apply a custom request predicate. Response predicates are applied the same way but using the response_predicate function on LiveReloadLayer.

use axum::{http::Request, response::Html, routing::get, Router};
use tower_livereload::LiveReloadLayer;

fn not_htmx_predicate<Body>(req: &Request<Body>) -> bool {
    !req.headers().contains_key("hx-request")
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let app = Router::new()
        .route("/", get(|| async { Html("<h1>Wow, such webdev</h1>") }))
        .layer(LiveReloadLayer::new().request_predicate(not_htmx_predicate));

    axum::Server::bind(&"0.0.0.0:3030".parse()?)
        .serve(app.into_make_service())
        .await?;

    Ok(())
}

@wrapperup you can test if this code works for your use-case. Any feedback is appreciated!

Would close #2

wrapperup commented 1 year ago

Works great. Thanks!