Skip to main content

ContentNegotiation

Struct ContentNegotiation 

Source
pub struct ContentNegotiation { /* private fields */ }
Expand description

Plugin that converts plain-text error responses into structured JSON.

When installed, ContentNegotiation wraps the request pipeline with a middleware that inspects every outgoing response. If the status is a client error (4xx) or server error (5xx) and the Content-Type is text/plain, it re-encodes the body as:

{"error": "<original message>", "status": <status code>}

This ensures that API clients always receive a machine-readable JSON error body rather than an opaque string, regardless of where in the framework the error originated.

§Configuration

Builder methodDefaultDescription
prettyfalsePretty-print the JSON error body

§Example

use churust_core::{Churust, Call, Error, TestClient};
use churust_json::ContentNegotiation;

let app = Churust::server()
    .install(ContentNegotiation::new())
    .routing(|r| {
        r.get("/fail", |_c: Call| async {
            Err::<&str, _>(Error::bad_request("something went wrong"))
        });
    })
    .build();

let res = TestClient::new(app).get("/fail").send().await;
assert_eq!(res.status().as_u16(), 400);
assert_eq!(res.header("content-type"), Some("application/json"));

let body: serde_json::Value = serde_json::from_slice(res.body_bytes()).unwrap();
assert_eq!(body["error"], "something went wrong");
assert_eq!(body["status"], 400);

Implementations§

Source§

impl ContentNegotiation

Source

pub fn new() -> Self

Creates a new ContentNegotiation plugin with default settings.

By default, JSON error bodies are compact (not pretty-printed). Call pretty on the returned value to change this.

§Example
use churust_core::{Churust, Call, Error, TestClient};
use churust_json::ContentNegotiation;

let app = Churust::server()
    .install(ContentNegotiation::new())
    .routing(|r| {
        r.get("/boom", |_c: Call| async {
            Err::<&str, _>(Error::not_found("no such resource"))
        });
    })
    .build();

let res = TestClient::new(app).get("/boom").send().await;
assert_eq!(res.header("content-type"), Some("application/json"));
Source

pub fn pretty(self, pretty: bool) -> Self

Controls whether JSON error bodies are pretty-printed.

When pretty is true, error responses are formatted with newlines and indentation, which is helpful during development or when error responses may be read by humans. For production APIs, leave this at the default false to keep response sizes small.

§Parameters
  • prettytrue to enable pretty-printing; false (the default) for compact output.
§Example
use churust_core::{Churust, Call, Error, TestClient};
use churust_json::ContentNegotiation;

let app = Churust::server()
    .install(ContentNegotiation::new().pretty(true))
    .routing(|r| {
        r.get("/oops", |_c: Call| async {
            Err::<&str, _>(Error::internal("disk full"))
        });
    })
    .build();

let res = TestClient::new(app).get("/oops").send().await;
assert_eq!(res.status().as_u16(), 500);
// Pretty-printed JSON contains newlines.
let text = res.text();
assert!(text.contains('\n'));

Trait Implementations§

Source§

impl Clone for ContentNegotiation

Source§

fn clone(&self) -> ContentNegotiation

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ContentNegotiation

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for ContentNegotiation

Source§

fn default() -> ContentNegotiation

Returns the “default value” for a type. Read more
Source§

impl Plugin for ContentNegotiation

Source§

fn install(self: Box<Self>, app: &mut AppBuilder)

Install this plugin into the builder (register middleware, state, etc.). Consumes the boxed plugin.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more