1
0
mirror of https://github.com/actix/actix-website synced 2025-01-22 16:15:56 +01:00

use Bytes re-export

closes #202
This commit is contained in:
Rob Ede 2020-11-27 01:10:05 +00:00
parent c39325a649
commit cdbb5dd2b2
No known key found for this signature in database
GPG Key ID: C2A3B36E841A91E6
12 changed files with 31 additions and 25 deletions

View File

@ -80,7 +80,7 @@ Actix-web also provides several other extractors:
need access to the request. need access to the request.
* *String* - You can convert a request's payload to a *String*. [*Example*][stringexample] * *String* - You can convert a request's payload to a *String*. [*Example*][stringexample]
is available in doc strings. is available in doc strings.
* *bytes::Bytes* - You can convert a request's payload into *Bytes*. * *actix_web::web::Bytes* - You can convert a request's payload into *Bytes*.
[*Example*][bytesexample] [*Example*][bytesexample]
is available in doc strings. is available in doc strings.
* *Payload* - You can access a request's payload. * *Payload* - You can access a request's payload.

View File

@ -38,7 +38,7 @@ complex types are involved.
```rust ```rust
async fn index(_req: HttpRequest) -> impl Responder { async fn index(_req: HttpRequest) -> impl Responder {
Bytes::from_static(b"Hello world!") web::Bytes::from_static(b"Hello world!")
} }
``` ```

View File

@ -1,12 +1,10 @@
// <stream> // <stream>
use actix_web::{get, App, Error, HttpResponse, HttpServer}; use actix_web::{get, web, App, Error, HttpResponse, HttpServer};
use bytes::Bytes; use futures::{future::ok, stream::once};
use futures::future::ok;
use futures::stream::once;
#[get("/stream")] #[get("/stream")]
async fn stream() -> HttpResponse { async fn stream() -> HttpResponse {
let body = once(ok::<_, Error>(Bytes::from_static(b"test"))); let body = once(ok::<_, Error>(web::Bytes::from_static(b"test")));
HttpResponse::Ok() HttpResponse::Ok()
.content_type("application/json") .content_type("application/json")

View File

@ -1,7 +1,7 @@
// <logging> // <logging>
use actix_web::{error, get, middleware::Logger, App, HttpServer, Result}; use actix_web::{error, get, middleware::Logger, App, HttpServer, Result};
use log::debug;
use derive_more::{Display, Error}; use derive_more::{Display, Error};
use log::debug;
#[derive(Debug, Display, Error)] #[derive(Debug, Display, Error)]
#[display(fmt = "my error: {}", name)] #[display(fmt = "my error: {}", name)]

View File

@ -1,7 +1,7 @@
#![allow(dead_code)] #![allow(dead_code)]
// <json-two> // <json-two>
use actix_web::{error, web, App, FromRequest, HttpResponse, HttpServer, Responder}; use actix_web::{error, web, App, HttpResponse, HttpServer, Responder};
use serde::Deserialize; use serde::Deserialize;
#[derive(Deserialize)] #[derive(Deserialize)]

View File

@ -2,7 +2,6 @@
use actix_web::{error, post, web, App, Error, HttpResponse}; use actix_web::{error, post, web, App, Error, HttpResponse};
use futures::StreamExt; use futures::StreamExt;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json;
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
struct MyObj { struct MyObj {

View File

@ -1,7 +1,7 @@
// <responder-trait> // <responder-trait>
use actix_web::{Error, HttpRequest, HttpResponse, Responder}; use actix_web::{Error, HttpRequest, HttpResponse, Responder};
use serde::Serialize;
use futures::future::{ready, Ready}; use futures::future::{ready, Ready};
use serde::Serialize;
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {

View File

@ -1,12 +1,11 @@
// <chunked> // <chunked>
use actix_web::{get, App, Error, HttpRequest, HttpResponse, HttpServer}; use actix_web::{get, web, App, Error, HttpRequest, HttpResponse, HttpServer};
use bytes::Bytes;
use futures::future::ok; use futures::future::ok;
use futures::stream::once; use futures::stream::once;
#[get("/")] #[get("/")]
async fn index(_req: HttpRequest) -> HttpResponse { async fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::Ok().streaming(once(ok::<_, Error>(Bytes::from_static(b"data")))) HttpResponse::Ok().streaming(once(ok::<_, Error>(web::Bytes::from_static(b"data"))))
} }
// </chunked> // </chunked>

View File

@ -1,5 +1,5 @@
// <signals> // <signals>
use actix_web::{web, App, HttpResponse, HttpServer, rt::System}; use actix_web::{rt::System, web, App, HttpResponse, HttpServer};
use std::sync::mpsc; use std::sync::mpsc;
use std::thread; use std::thread;

View File

@ -14,7 +14,8 @@ async fn main() -> std::io::Result<()> {
// load ssl keys // load ssl keys
// to create a self-signed temporary cert for testing: // to create a self-signed temporary cert for testing:
// `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'` // `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); let mut builder =
SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
builder builder
.set_private_key_file("key.pem", SslFiletype::PEM) .set_private_key_file("key.pem", SslFiletype::PEM)
.unwrap(); .unwrap();

View File

@ -23,7 +23,8 @@ mod tests {
App::new() App::new()
.data(AppState { count: 4 }) .data(AppState { count: 4 })
.route("/", web::get().to(index)), .route("/", web::get().to(index)),
).await; )
.await;
let req = test::TestRequest::get().uri("/").to_request(); let req = test::TestRequest::get().uri("/").to_request();
let resp: AppState = test::read_response_json(&mut app, req).await; let resp: AppState = test::read_response_json(&mut app, req).await;

View File

@ -1,22 +1,21 @@
// <stream-response> // <stream-response>
use std::task::Poll;
use bytes::Bytes;
use futures::stream::poll_fn; use futures::stream::poll_fn;
use std::task::Poll;
use actix_web::http::{ContentEncoding, StatusCode}; use actix_web::http::{ContentEncoding, StatusCode};
use actix_web::{web, http, App, Error, HttpRequest, HttpResponse}; use actix_web::{http, web, App, Error, HttpRequest, HttpResponse};
async fn sse(_req: HttpRequest) -> HttpResponse { async fn sse(_req: HttpRequest) -> HttpResponse {
let mut counter: usize = 5; let mut counter: usize = 5;
// yields `data: N` where N in [5; 1] // yields `data: N` where N in [5; 1]
let server_events = poll_fn(move |_cx| -> Poll<Option<Result<Bytes, Error>>> { let server_events = poll_fn(move |_cx| -> Poll<Option<Result<web::Bytes, Error>>> {
if counter == 0 { if counter == 0 {
return Poll::Ready(None); return Poll::Ready(None);
} }
let payload = format!("data: {}\n\n", counter); let payload = format!("data: {}\n\n", counter);
counter -= 1; counter -= 1;
Poll::Ready(Some(Ok(Bytes::from(payload)))) Poll::Ready(Some(Ok(web::Bytes::from(payload))))
}); });
HttpResponse::build(StatusCode::OK) HttpResponse::build(StatusCode::OK)
@ -51,15 +50,24 @@ mod tests {
// first chunk // first chunk
let (bytes, mut resp) = resp.take_body().into_future().await; let (bytes, mut resp) = resp.take_body().into_future().await;
assert_eq!(bytes.unwrap().unwrap(), Bytes::from_static(b"data: 5\n\n")); assert_eq!(
bytes.unwrap().unwrap(),
web::Bytes::from_static(b"data: 5\n\n")
);
// second chunk // second chunk
let (bytes, mut resp) = resp.take_body().into_future().await; let (bytes, mut resp) = resp.take_body().into_future().await;
assert_eq!(bytes.unwrap().unwrap(), Bytes::from_static(b"data: 4\n\n")); assert_eq!(
bytes.unwrap().unwrap(),
web::Bytes::from_static(b"data: 4\n\n")
);
// remaining part // remaining part
let bytes = test::load_stream(resp.take_body().into_stream()).await; let bytes = test::load_stream(resp.take_body().into_stream()).await;
assert_eq!(bytes.unwrap(), Bytes::from_static(b"data: 3\n\ndata: 2\n\ndata: 1\n\n")); assert_eq!(
bytes.unwrap(),
web::Bytes::from_static(b"data: 3\n\ndata: 2\n\ndata: 1\n\n")
);
} }
} }
// </stream-response> // </stream-response>