#proc-macro #procmacro #actix-web #actix #actix-responder

macro actix_responder_macro

An attribute macro to transform a response struct to an actix responder

4 releases

0.0.4 Dec 1, 2020
0.0.3 Nov 29, 2020
0.0.2 Nov 29, 2020
0.0.1 Nov 27, 2020

#1139 in Procedural macros

Download history 1/week @ 2022-01-29 1/week @ 2022-02-05 5/week @ 2022-02-12 4/week @ 2022-02-19 14/week @ 2022-03-12 19/week @ 2022-03-19 3/week @ 2022-03-26 1/week @ 2022-04-09 1/week @ 2022-04-16 8/week @ 2022-04-23 9/week @ 2022-04-30 33/week @ 2022-05-07

51 downloads per month

MIT/Apache

11KB
200 lines

actix-responder-macro

An attribute macro to transform a handler response struct to an actix responder. Keeps flexibility while adding more type safety.

The actix_responder adds 2 additional fields to your struct content_type and status_code. The meta_attr allows for arbitrary attributes to both fields.

status_attr applies only to status_code and content_attr applies only to content_type

The reason for this is like in the example below, if you use a crate like TypedBuilder, you might want to apply options like #[builder(default)] to the generated field.

The macro always applies #[serde(skip)] to both generated fields so they won't show up in the request response.

#[actix_responder(meta_attr = "builder(default)")]
#[derive(TypedBuilder, Serialize, Deserialize)]
pub struct SuccessResp {
    success: bool,
}

From this

#[get("/health_check")]
pub async fn health_check() -> impl Responder {
    HttpResponse::Ok()
    .set_header(header::CONTENT_TYPE, mime::APPLICATION_JSON)
    .json(SuccessResp { success: true })
}

to this

#[get("/health_check")]
pub async fn health_check() -> SuccessResp {
    SuccessResp::builder()
    .success(true)
    .content_type(mime::APPLICATION_JSON::to_string())
    .build()
}

A more complicated example with setting default values

extern crate actix_responder_macro;
extern crate mime;
extern crate typed_builder;

use actix_responder_macro::actix_responder;
use actix_web::http::StatusCode;
use serde::{Deserialize, Serialize};
use typed_builder::TypedBuilder;

#[actix_responder(
    status_attr = "builder(default = StatusCode::INTERNAL_SERVER_ERROR)",
    content_attr = "builder(default = mime::IMAGE_BMP.to_string())"
)]
#[derive(Serialize, Deserialize, Debug, TypedBuilder, Default)]
pub struct ImageResp {...}

Dependencies

~295–710KB
~17K SLoC