mirror of
https://github.com/actix/examples
synced 2024-11-23 22:41:07 +01:00
refactor basics/basics
This commit is contained in:
parent
8dcc610d23
commit
07384c91aa
4
Cargo.lock
generated
4
Cargo.lock
generated
@ -1390,11 +1390,11 @@ version = "2.0.0"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"actix-files 0.6.0-beta.16",
|
"actix-files 0.6.0-beta.16",
|
||||||
"actix-session 0.5.0-beta.7",
|
"actix-session 0.5.0-beta.7",
|
||||||
"actix-utils 3.0.0",
|
|
||||||
"actix-web 4.0.0-rc.1",
|
"actix-web 4.0.0-rc.1",
|
||||||
|
"async-stream",
|
||||||
"env_logger 0.9.0",
|
"env_logger 0.9.0",
|
||||||
|
"log",
|
||||||
"tokio 1.16.1",
|
"tokio 1.16.1",
|
||||||
"tokio-stream",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
|
@ -8,7 +8,8 @@ edition = "2018"
|
|||||||
actix-web = "4.0.0-beta.21"
|
actix-web = "4.0.0-beta.21"
|
||||||
actix-files = "0.6.0-beta.15"
|
actix-files = "0.6.0-beta.15"
|
||||||
actix-session = "0.5.0-beta.7"
|
actix-session = "0.5.0-beta.7"
|
||||||
actix-utils = "3"
|
|
||||||
tokio = "1"
|
async-stream = "0.3"
|
||||||
tokio-stream = "0.1"
|
|
||||||
env_logger = "0.9"
|
env_logger = "0.9"
|
||||||
|
log = "0.4"
|
||||||
|
tokio = "1"
|
||||||
|
@ -1,23 +1,28 @@
|
|||||||
use actix_files as fs;
|
use std::convert::Infallible;
|
||||||
|
use std::io;
|
||||||
|
|
||||||
|
use actix_files::{Files, NamedFile};
|
||||||
use actix_session::{CookieSession, Session};
|
use actix_session::{CookieSession, Session};
|
||||||
use actix_web::http::{header, Method, StatusCode};
|
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
error, get, middleware, web, App, Either, Error, HttpRequest, HttpResponse,
|
error, get,
|
||||||
HttpServer, Result,
|
http::{
|
||||||
|
header::{self, ContentType},
|
||||||
|
Method, StatusCode,
|
||||||
|
},
|
||||||
|
middleware, web, App, Either, HttpRequest, HttpResponse, HttpServer, Responder,
|
||||||
|
Result,
|
||||||
};
|
};
|
||||||
use std::{env, io};
|
use async_stream::stream;
|
||||||
use tokio::sync::mpsc;
|
|
||||||
use tokio_stream::wrappers::UnboundedReceiverStream;
|
|
||||||
|
|
||||||
/// favicon handler
|
/// favicon handler
|
||||||
#[get("/favicon")]
|
#[get("/favicon")]
|
||||||
async fn favicon() -> Result<fs::NamedFile> {
|
async fn favicon() -> Result<impl Responder> {
|
||||||
Ok(fs::NamedFile::open("static/favicon.ico")?)
|
Ok(NamedFile::open("static/favicon.ico")?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// simple index handler
|
/// simple index handler
|
||||||
#[get("/welcome")]
|
#[get("/welcome")]
|
||||||
async fn welcome(session: Session, req: HttpRequest) -> Result<HttpResponse> {
|
async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {
|
||||||
println!("{:?}", req);
|
println!("{:?}", req);
|
||||||
|
|
||||||
// session
|
// session
|
||||||
@ -32,16 +37,14 @@ async fn welcome(session: Session, req: HttpRequest) -> Result<HttpResponse> {
|
|||||||
|
|
||||||
// response
|
// response
|
||||||
Ok(HttpResponse::build(StatusCode::OK)
|
Ok(HttpResponse::build(StatusCode::OK)
|
||||||
.content_type("text/html; charset=utf-8")
|
.content_type(ContentType::plaintext())
|
||||||
.body(include_str!("../static/welcome.html")))
|
.body(include_str!("../static/welcome.html")))
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn default_handler(
|
async fn default_handler(req_method: Method) -> Result<impl Responder> {
|
||||||
request: HttpRequest,
|
match req_method {
|
||||||
) -> Result<Either<fs::NamedFile, HttpResponse>> {
|
Method::GET => {
|
||||||
match *request.method() {
|
let file = NamedFile::open("static/404.html")?
|
||||||
actix_web::http::Method::GET => {
|
|
||||||
let file = fs::NamedFile::open("static/404.html")?
|
|
||||||
.set_status_code(StatusCode::NOT_FOUND);
|
.set_status_code(StatusCode::NOT_FOUND);
|
||||||
Ok(Either::Left(file))
|
Ok(Either::Left(file))
|
||||||
}
|
}
|
||||||
@ -51,12 +54,13 @@ async fn default_handler(
|
|||||||
|
|
||||||
/// response body
|
/// response body
|
||||||
async fn response_body(path: web::Path<String>) -> HttpResponse {
|
async fn response_body(path: web::Path<String>) -> HttpResponse {
|
||||||
let text = format!("Hello {}!", *path);
|
let name = path.into_inner();
|
||||||
|
|
||||||
let (tx, rx_body) = mpsc::unbounded_channel();
|
HttpResponse::Ok().streaming(stream! {
|
||||||
let _ = tx.send(Ok::<_, Error>(web::Bytes::from(text)));
|
yield Ok::<_, Infallible>(web::Bytes::from("Hello "));
|
||||||
|
yield Ok::<_, Infallible>(web::Bytes::from(name));
|
||||||
HttpResponse::Ok().streaming(UnboundedReceiverStream::from(rx_body))
|
yield Ok::<_, Infallible>(web::Bytes::from("!"));
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// handler with path parameters like `/user/{name}/`
|
/// handler with path parameters like `/user/{name}/`
|
||||||
@ -64,17 +68,20 @@ async fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpRespons
|
|||||||
println!("{:?}", req);
|
println!("{:?}", req);
|
||||||
|
|
||||||
HttpResponse::Ok()
|
HttpResponse::Ok()
|
||||||
.content_type("text/plain")
|
.content_type(ContentType::plaintext())
|
||||||
.body(format!("Hello {}!", path.0))
|
.body(format!("Hello {}!", path.0))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> io::Result<()> {
|
async fn main() -> io::Result<()> {
|
||||||
env::set_var("RUST_LOG", "actix_web=debug,actix_server=info");
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
env_logger::init();
|
|
||||||
|
log::info!("starting HTTP server at http://localhost:8080");
|
||||||
|
|
||||||
HttpServer::new(|| {
|
HttpServer::new(|| {
|
||||||
App::new()
|
App::new()
|
||||||
|
// enable automatic response compression - usually register this first
|
||||||
|
.wrap(middleware::Compress::default())
|
||||||
// cookie session middleware
|
// cookie session middleware
|
||||||
.wrap(CookieSession::signed(&[0; 32]).secure(false))
|
.wrap(CookieSession::signed(&[0; 32]).secure(false))
|
||||||
// enable logger - always register actix-web Logger middleware last
|
// enable logger - always register actix-web Logger middleware last
|
||||||
@ -103,18 +110,21 @@ async fn main() -> io::Result<()> {
|
|||||||
)
|
)
|
||||||
}))
|
}))
|
||||||
// static files
|
// static files
|
||||||
.service(fs::Files::new("/static", "static").show_files_listing())
|
.service(Files::new("/static", "static").show_files_listing())
|
||||||
// redirect
|
// redirect
|
||||||
.service(web::resource("/").route(web::get().to(|req: HttpRequest| {
|
.service(web::resource("/").route(web::get().to(
|
||||||
println!("{:?}", req);
|
|req: HttpRequest| async move {
|
||||||
HttpResponse::Found()
|
println!("{:?}", req);
|
||||||
.insert_header((header::LOCATION, "static/welcome.html"))
|
HttpResponse::Found()
|
||||||
.finish()
|
.insert_header((header::LOCATION, "static/welcome.html"))
|
||||||
})))
|
.finish()
|
||||||
|
},
|
||||||
|
)))
|
||||||
// default
|
// default
|
||||||
.default_service(web::route().to(default_handler))
|
.default_service(web::to(default_handler))
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind(("127.0.0.1", 8080))?
|
||||||
|
.workers(2)
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user