Module axum_valid::msgpack

source ·
Expand description

Support for MsgPack<T> and MsgPackRaw<T> from axum-msgpack

Feature

Enable the msgpack feature to use Valid<MsgPack<T>> and Valid<MsgPackRaw<T>>.

Usage

  1. Implement Deserialize and Validate for your data type T.
  2. In your handler function, use Valid<MsgPack<T>> or Valid<MsgPackRaw<T>> as some parameter’s type.

Example

use axum::routing::post;
use axum::Router;
use axum_msgpack::{MsgPack, MsgPackRaw};
use axum_valid::Valid;
use serde::Deserialize;
use validator::Validate;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let router = Router::new()
        .route("/msgpack", post(handler))
        .route("/msgpackraw", post(raw_handler));
    axum::Server::bind(&([0u8, 0, 0, 0], 8080).into())
        .serve(router.into_make_service())
        .await?;
    Ok(())
}

async fn handler(Valid(MsgPack(parameter)): Valid<MsgPack<Parameter>>) {
    assert!(parameter.validate().is_ok());
}

async fn raw_handler(Valid(MsgPackRaw(parameter)): Valid<MsgPackRaw<Parameter>>) {
    assert!(parameter.validate().is_ok());
}

#[derive(Validate, Deserialize)]
pub struct Parameter {
    #[validate(range(min = 5, max = 10))]
    pub v0: i32,
    #[validate(length(min = 1, max = 10))]
    pub v1: String,
}