Skip to main content

Response

Struct Response 

Source
pub struct Response {
    pub status: Status,
    pub headers: ResponseHeaders,
    /* private fields */
}
Expand description

§HTTP Response

Composed of

  • status
  • headers
  • content

§Usage

in_fang.rs

use ohkami::prelude::*;

#[derive(Clone)]
struct SetHeaders;
impl FangAction for SetHeaders {
    async fn back<'a>(&'a self, res: &'a mut Response) {
        res.headers.set()
            .server("ohkami")
            .vary("Origin");
    }
}

#[tokio::main]
async fn main() {
    Ohkami::new((SetHeaders,
        "/".GET(|| async {"Hello, ohkami!"})
    )).howl("localhost:5050").await
}

into_response.rs

use ohkami::{Response, IntoResponse, Status};

enum AppError {
    A(String),
    B(String),
}
impl IntoResponse for AppError {
    fn into_response(self) -> Response {
        match self {
            Self::A(msg) => Response::InternalServerError().with_text(msg),
            Self::B(msg) => Response::BadRequest().with_text(msg),
        }
    }
}

async fn handler(id: usize) -> Result<String, AppError> {
    if id == 0 {
        return Err(AppError::B("id must be positive".into()))
    }

    Ok("Hello, Response!".into())
}

Fields§

§status: Status

HTTP status of this response

§headers: ResponseHeaders

Headers of this response

  • .{name}(), .get("{name}") to get value
  • .set().{name}({action}), .set().x("{name}", {action}) to mutate values

{action}:

  • just {value} to insert
  • None to remove
  • header::append({value}) to append

{value}:

  • String
  • &'static str
  • Cow<'static, str>
  • Some(Cow<'static, str>)

Implementations§

Source§

impl Response

Source

pub fn Continue() -> Self

100 Continue empty Response

Source

pub fn SwitchingProtocols() -> Self

101 Switching Protocols empty Response

Source

pub fn Processing() -> Self

102 Processing empty Response

Source

pub fn EarlyHints() -> Self

103 Early Hints empty Response

Source

pub fn OK() -> Self

200 OK empty Response

Source

pub fn Created() -> Self

201 Created empty Response

Source

pub fn Accepted() -> Self

202 Accepted empty Response

Source

pub fn NonAuthoritativeInformation() -> Self

203 Non-Authoritative Information empty Response

Source

pub fn NoContent() -> Self

204 No Content empty Response

Source

pub fn ResetContent() -> Self

205 Reset Content empty Response

Source

pub fn PartialContent() -> Self

206 Partial Content empty Response

Source

pub fn MultiStatus() -> Self

207 Multi-Status empty Response

Source

pub fn AlreadyReported() -> Self

208 Already Reported empty Response

Source

pub fn IMUsed() -> Self

226 IMUsed empty Response

Source

pub fn MultipleChoice() -> Self

300 Multiple Choice empty Response

Source

pub fn MovedPermanently() -> Self

301 Moved Permanently empty Response

Source

pub fn Found() -> Self

302 Found empty Response

Source

pub fn SeeOther() -> Self

303 See Other empty Response

Source

pub fn NotModified() -> Self

304 Not Modifed empty Response

Source

pub fn TemporaryRedirect() -> Self

307 Temporary Redirect empty Response

Source

pub fn PermanentRedirect() -> Self

308 Permanent Redirect empty Response

Source

pub fn BadRequest() -> Self

400 Bad Request empty Response

Source

pub fn Unauthorized() -> Self

401 Unauthorized empty Response

Source

pub fn Forbidden() -> Self

403 Forbidden empty Response

Source

pub fn NotFound() -> Self

404 Not Found empty Response

Source

pub fn MethodNotAllowed() -> Self

405 Method Not Allowed empty Response

Source

pub fn NotAcceptable() -> Self

406 Not Acceptable empty Response

Source

pub fn ProxyAuthenticationRequired() -> Self

407 Proxy Authentication Required empty Response

Source

pub fn RequestTimeout() -> Self

408 Request Timeout empty Response

Source

pub fn Conflict() -> Self

409 Conflict empty Response

Source

pub fn Gone() -> Self

410 Gone empty Response

Source

pub fn LengthRequired() -> Self

411 Length Required empty Response

Source

pub fn PreconditionFailed() -> Self

412 Precondition Failed empty Response

Source

pub fn PayloadTooLarge() -> Self

413 Payload Too Large empty Response

Source

pub fn URITooLong() -> Self

414 URI Too Long empty Response

Source

pub fn UnsupportedMediaType() -> Self

415 Unsupported Media Type empty Response

Source

pub fn RangeNotSatisfiable() -> Self

416 Range Not Satisfiable empty Response

Source

pub fn ExceptionFailed() -> Self

417 Exception Failed empty Response

Source

pub fn ImATeapot() -> Self

418 I'm a teapot empty Response

Source

pub fn MisdirectedRequest() -> Self

421 Misdirected Request empty Response

Source

pub fn UnprocessableEntity() -> Self

422 Unprocessable Entity empty Response

Source

pub fn Locked() -> Self

423 Locked empty Response

Source

pub fn FailedDependency() -> Self

424 Failed Dependency empty Response

Source

pub fn UpgradeRequired() -> Self

426 UpgradeRequired empty Response

Source

pub fn PreconditionRequired() -> Self

428 Precondition Required empty Response

Source

pub fn TooManyRequest() -> Self

429 Too Many Request empty Response

Source

pub fn RequestHeaderFieldsTooLarge() -> Self

431 Request Header Fields Too Large empty Response

Source

pub fn UnavailableForLegalReasons() -> Self

451 Unavailable For Legal Reasons empty Response

Source

pub fn InternalServerError() -> Self

500 Internal Server Error empty Response

Source

pub fn NotImplemented() -> Self

501 Not Implemented empty Response

Source

pub fn BadGateway() -> Self

502 Bad Gateway empty Response

Source

pub fn ServiceUnavailable() -> Self

503 Service Unavailable empty Response

Source

pub fn GatewayTimeout() -> Self

504 Gateway Timeout empty Response

Source

pub fn HTTPVersionNotSupported() -> Self

505 HTTP Version Not Supported empty Response

Source

pub fn VariantAlsoNegotiates() -> Self

506 Variant Also Negotiates empty Response

Source

pub fn InsufficientStorage() -> Self

507 Unsufficient Storage empty Response

Source

pub fn LoopDetected() -> Self

508 Loop Detected empty Response

Source

pub fn NotExtended() -> Self

510 Not Extended empty Response

Source

pub fn NetworkAuthenticationRequired() -> Self

511 Network Authentication Required empty Response

Source§

impl Response

Source

pub fn new(status: Status) -> Self

Source§

impl Response

Source

pub fn with_headers( self, f: impl FnOnce(SetHeaders<'_>) -> SetHeaders<'_>, ) -> Self

Source

pub fn drop_content(&mut self) -> Content

Source

pub fn without_content(self) -> Self

Source

pub fn set_payload( &mut self, content_type: &'static str, content: impl Into<Cow<'static, [u8]>>, )

Source

pub fn with_payload( self, content_type: &'static str, content: impl Into<Cow<'static, [u8]>>, ) -> Self

Source

pub fn payload(&self) -> Option<&[u8]>

Source

pub fn set_text<Text: Into<Cow<'static, str>>>(&mut self, text: Text)

Source

pub fn with_text<Text: Into<Cow<'static, str>>>(self, text: Text) -> Self

Source

pub fn set_html<HTML: Into<Cow<'static, str>>>(&mut self, html: HTML)

Source

pub fn with_html<HTML: Into<Cow<'static, str>>>(self, html: HTML) -> Self

Source

pub fn set_json<JSON: Serialize>(&mut self, json: JSON)

Source

pub fn with_json<JSON: Serialize>(self, json: JSON) -> Self

Source

pub unsafe fn set_json_lit<JSONLiteral: Into<Cow<'static, str>>>( &mut self, json_lit: JSONLiteral, )

§SAFETY

argument json_lit must be valid JSON

Source

pub unsafe fn with_json_lit<JSONLiteral: Into<Cow<'static, str>>>( self, json_lit: JSONLiteral, ) -> Self

§SAFETY

argument json_lit must be valid JSON

Source§

impl Response

Source

pub fn with_stream<T: Data>( self, stream: impl Stream<Item = T> + Unpin + Send + 'static, ) -> Self

Available on crate feature sse only.
Source

pub fn set_stream<T: Data>( &mut self, stream: impl Stream<Item = T> + Unpin + Send + 'static, )

Available on crate feature sse only.
Source

pub fn set_stream_raw( &mut self, stream: Pin<Box<dyn Stream<Item = String> + Send>>, )

Available on crate feature sse only.

Trait Implementations§

Source§

impl Debug for Response

Source§

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

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

impl FromResidual<Result<Infallible, Response>> for Response

Available on crate feature nightly only.
Source§

fn from_residual(residual: Result<Infallible, Response>) -> Self

🔬This is a nightly-only experimental API. (try_trait_v2)
Constructs the type from a compatible Residual type. Read more
Source§

impl IntoResponse for Response

Source§

impl PartialEq for Response

Source§

fn eq(&self, other: &Self) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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> Same for T

Source§

type Output = T

Should always be Self
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> SendOnThreaded for T
where T: Send,