hyper-method-override-middleware

Crates.iohyper-method-override-middleware
lib.rshyper-method-override-middleware
version1.0.0
sourcesrc
created_at2020-10-04 17:21:26.658645
updated_at2020-10-04 17:24:56.727282
descriptionA Hyper service middleware that overrides HTTP methods based on a _method query param, to allow web browsers to simulate non GET/POST requests.
homepage
repositoryhttps://github.com/lpil/hyper-method-override-middleware
max_upload_size
id296089
size20,407
Louis Pilfold (lpil)

documentation

README

Hyper Method Override Middleware

crates.io Documentation Apache-2 licensed

A middleware for Hyper that overrides an incoming POST request with a method given in the request's _method query paramerter. This is useful as web browsers typically only support GET and POST requests, but our application may expect other HTTP methods that are more semantically correct.

The methods PUT, PATCH, and DELETE are accepted for overriding, all others are ignored.

The _method query paramerter can be specified in a HTML form like so:

<form method="POST" action="/item/1?_method=DELETE">
    <button type="submit">Delete item</button>
</form>

And the middleware can be applied to our Hyper service like so:

let service = MethodOverrideMiddleware::new(service);

Full example

Here's the example from the Hyper homepage with the middleware applied.

use std::{convert::Infallible, net::SocketAddr};
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};

async fn handle(_: Request<Body>) -> Result<Response<Body>, Infallible> {
    Ok(Response::new("Hello, World!".into()))
}

#[tokio::main]
async fn main() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    let make_svc = make_service_fn(|_conn| async {
        let service = MethodOverrideMiddleware::new(service_fn(handle));
        Ok::<_, Infallible>(service)
    });

    let server = Server::bind(&addr).serve(make_svc);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}
Commit count: 7

cargo fmt