http_request_derive/http_request_body.rs
1// SPDX-FileCopyrightText: OpenTalk GmbH <mail@opentalk.eu>
2//
3// SPDX-License-Identifier: MIT OR Apache-2.0
4
5use http::HeaderMap;
6
7use crate::Error;
8
9/// Trait defined on every body type that can be used with [`crate::HttpRequest`].
10pub trait HttpRequestBody {
11 /// Convert the request contents to a [`Vec<u8>`].
12 ///
13 /// # Errors
14 ///
15 /// If the conversion to the [`Vec`] goes wrong, this will be indicated by
16 /// returning an appropriate [`Error`].
17 fn to_vec(&self) -> Result<Vec<u8>, Error>;
18
19 /// Apply the headers that this body requires for the request to be valid.
20 /// This will usually add a [`http::header::CONTENT_TYPE`] header.
21 fn apply_headers(&self, _headers: &mut HeaderMap) {}
22}
23
24#[cfg(feature = "serde")]
25impl<B: serde::Serialize> HttpRequestBody for B {
26 fn to_vec(&self) -> Result<Vec<u8>, Error> {
27 use snafu::ResultExt;
28 serde_json::to_vec(self).context(crate::error::JsonSnafu)
29 }
30
31 fn apply_headers(&self, headers: &mut HeaderMap) {
32 let _ = headers
33 .entry(http::header::CONTENT_TYPE)
34 .or_insert_with(|| http::HeaderValue::from_static("application/json"));
35 }
36}