Crate axum_media

source ·
Expand description

github crates.io docs.rs


This crate provides a simple way to use multiple mime types for serializing and deserializing structs within the axum ecosystem. Inspired by axum’s Json extractor.

Example

use axum_media::{AnyMedia, Accept};
#[tokio::main]
async fn main() {
  let app = axum::Router::new()
    .route("/", axum::routing::get(index))
    .route("/login", axum::routing::post(login));

  axum::Server::bind(&"127.0.0.1:3000".parse().unwrap())
    .serve(app.into_make_service())
    .await.unwrap();
}

async fn index(accept: Accept) -> impl axum::response::IntoResponse {
  // Chooses the right serializer based on the Accept header
  AnyMedia(
    serde_json::json!({
      "routes": ["/", "/login"],
    }),
    accept.into(),
  )
}

#[derive(serde::Deserialize)]
struct LoginData {
  email: String,
  password: String,
}

// Automatically chooses the right deserializer based on the Content-Type header
async fn login(AnyMedia(data, _): AnyMedia<LoginData>) -> String {
  data.email
}

Features

  • urlencoded - Enables support for application/x-www-form-urlencoded using [serde_urlencoded].

Structs

  • Accept header extractor.
  • Automatic data extractor / response.

Enums