http-query 0.2.0

A client and server SDK for the HTTP QUERY method (RFC 10008).
Documentation
//! A minimal axum server that handles the HTTP QUERY method using the
//! framework-agnostic helpers in [`http_query::server`].
//!
//! Run it with:
//!
//! ```sh
//! cargo run --example axum_server
//! ```
//!
//! Then send a QUERY request, e.g. with curl:
//!
//! ```sh
//! curl -X QUERY http://127.0.0.1:3000/search \
//!   -H 'content-type: application/sql' --data 'select 1'
//! ```

use axum::{
    body::{to_bytes, Body},
    extract::Request,
    response::Response,
    routing::any,
    Router,
};
use http_query::server::{accept_query_header, check_query_request, QueryRejection};

const ACCEPT_QUERY: &[&str] = &["application/json", "application/sql"];

async fn handle(req: Request) -> Response {
    let (parts, body) = req.into_parts();

    match check_query_request(parts.method.as_str(), &parts.headers, ACCEPT_QUERY) {
        Ok(()) => {
            let body = to_bytes(body, 1 << 20).await.unwrap_or_default();
            // Echo the query back as the result, and point at a GET-retrievable
            // result resource via Content-Location (RFC 10008 ยง2.3).
            Response::builder()
                .header("content-type", "application/json")
                .header("content-location", "/results/1")
                .body(Body::from(body))
                .unwrap()
        }
        Err(rejection) => {
            let mut builder = Response::builder()
                .status(rejection.status())
                .header("accept-query", accept_query_header(ACCEPT_QUERY));
            if rejection == QueryRejection::NotQuery {
                builder = builder.header("allow", "GET, QUERY, OPTIONS");
            }
            builder.body(Body::empty()).unwrap()
        }
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/search", any(handle));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("listening on http://127.0.0.1:3000 (try: QUERY /search)");
    axum::serve(listener, app).await.unwrap();
}