Basic基础
actix_web基础
#[get("/favicon")]
获取静态图片
#[get("/welcome")]
简单的欢迎
#`/user/{name}/`
basic.rs源码
源码
use std::{convert::Infallible, io};
use actix_files::{Files, NamedFile};
use actix_session::{storage::CookieSessionStore, Session, SessionMiddleware};
use actix_web::{
error, get,
http::{
header::{self, ContentType},
Method, StatusCode,
},
middleware, web, App, Either, HttpRequest, HttpResponse, HttpServer, Responder, Result,
};
use async_stream::stream;
// NOTE: Not a suitable session key for production.
static SESSION_SIGNING_KEY: &[u8] = &[0; 64];
/// favicon handler
#[get("/favicon")]
async fn favicon() -> Result<impl Responder> {
Ok(NamedFile::open("static/favicon.ico")?)
}
/// simple index handler
#[get("/welcome")]
async fn welcome(req: HttpRequest, session: Session) -> Result<HttpResponse> {
println!("{req:?}");
// session
let mut counter = 1;
if let Some(count) = session.get::<i32>("counter")? {
println!("SESSION value: {count}");
counter = count + 1;
}
// set counter to session
session.insert("counter", counter)?;
// response
Ok(HttpResponse::build(StatusCode::OK)
.content_type(ContentType::plaintext())
.body(include_str!("../static/welcome.html")))
}
async fn default_handler(req_method: Method) -> Result<impl Responder> {
match req_method {
Method::GET => {
let file = NamedFile::open("static/404.html")?
.customize()
.with_status(StatusCode::NOT_FOUND);
Ok(Either::Left(file))
}
_ => Ok(Either::Right(HttpResponse::MethodNotAllowed().finish())),
}
}
/// response body
async fn response_body(path: web::Path<String>) -> HttpResponse {
let name = path.into_inner();
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.streaming(stream! {
yield Ok::<_, Infallible>(web::Bytes::from("Hello "));
yield Ok::<_, Infallible>(web::Bytes::from(name));
yield Ok::<_, Infallible>(web::Bytes::from("!"));
})
}
/// handler with path parameters like `/user/{name}/`
async fn with_param(req: HttpRequest, path: web::Path<(String,)>) -> HttpResponse {
println!("{req:?}");
HttpResponse::Ok()
.content_type(ContentType::plaintext())
.body(format!("Hello {}!", path.0))
}
#[actix_web::main]
async fn main() -> io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
// random key means that restarting server will invalidate existing session cookies
let key = actix_web::cookie::Key::from(SESSION_SIGNING_KEY);
log::info!("starting HTTP server at http://localhost:8080");
HttpServer::new(move || {
App::new()
// enable automatic response compression - usually register this first
.wrap(middleware::Compress::default())
// cookie session middleware
.wrap(
SessionMiddleware::builder(CookieSessionStore::default(), key.clone())
.cookie_secure(false)
.build(),
)
// enable logger - always register Actix Web Logger middleware last
.wrap(middleware::Logger::default())
// register favicon
.service(favicon)
// register simple route, handle all methods
.service(welcome)
// with path parameters
.service(web::resource("/user/{name}").route(web::get().to(with_param)))
// async response body
.service(web::resource("/async-body/{name}").route(web::get().