1
0
mirror of https://github.com/actix/actix-website synced 2025-02-17 10:13:31 +01:00

moves individual examples to pub mods to force building and have less dead_code

This commit is contained in:
Cameron Dershem 2019-06-19 00:20:50 -04:00
parent a3cb721ed3
commit 4f9bd8b724
49 changed files with 226 additions and 191 deletions

View File

@ -23,7 +23,7 @@ The prefix should consist of value path segments.
> any request with the paths `/app`, `/app/`, or `/app/test` would match; > any request with the paths `/app`, `/app/`, or `/app/test` would match;
> however, the path `/application` would not match. > however, the path `/application` would not match.
{{< include-example example="application" section="make_app" >}} {{< include-example example="application" file="app.rs" section="setup" >}}
In this example, an application with the `/app` prefix and a `index.html` resource In this example, an application with the `/app` prefix and a `index.html` resource
are created. This resource is available through the `/app/index.html` url. are created. This resource is available through the `/app/index.html` url.
@ -33,7 +33,7 @@ are created. This resource is available through the `/app/index.html` url.
Multiple applications can be served with one server: Multiple applications can be served with one server:
{{< include-example example="application" section="run_server" >}} {{< include-example example="application" file="main.rs" section="run_server" >}}
All `/app1` requests route to the first application, `/app2` to the second, and all other to the third. All `/app1` requests route to the first application, `/app2` to the second, and all other to the third.
**Applications get matched based on registration order**. If an application with a more generic **Applications get matched based on registration order**. If an application with a more generic
@ -62,7 +62,6 @@ When the app is initialized it needs to be passed the initial state:
> must be constructed multiple times. If you want to share state between different threads, a > must be constructed multiple times. If you want to share state between different threads, a
> shared object should be used, e.g. `Arc`. There is also an [Example](https://github.com/actix/examples/blob/master/state/src/main.rs) using `Arc` for this. Application state does not need to be `Send` and `Sync`, > shared object should be used, e.g. `Arc`. There is also an [Example](https://github.com/actix/examples/blob/master/state/src/main.rs) using `Arc` for this. Application state does not need to be `Send` and `Sync`,
> but the application factory must be `Send` + `Sync`. > but the application factory must be `Send` + `Sync`.
>
To start the previous app, create it into a closure: To start the previous app, create it into a closure:
@ -76,7 +75,7 @@ Combining multiple applications with different state is possible as well.
This limitation can easily be overcome with the [App::boxed](https://docs.rs/actix-web/*/actix_web/struct.App.html#method.boxed) method, which converts an App into a boxed trait object. This limitation can easily be overcome with the [App::boxed](https://docs.rs/actix-web/*/actix_web/struct.App.html#method.boxed) method, which converts an App into a boxed trait object.
{{< include-example example="application" file="state.rs" section="combine" >}} {{< include-example example="application" file="combine.rs" section="combine" >}}
## Using an Application Scope to Compose Applications ## Using an Application Scope to Compose Applications

View File

@ -11,20 +11,20 @@ members = [
"url-dispatch", "url-dispatch",
"responder-trait", "responder-trait",
"either", "either",
]
exclude = [
"request-handlers",
"async-handlers",
"extractors", "extractors",
"autoreload", "autoreload",
"errors", "errors",
"requests", "requests",
"responses", "responses",
"testing",
"middleware", "middleware",
"static-files", "static-files",
"websockets",
"http2", "http2",
]
exclude = [
"testing",
"async-handlers",
"websockets",
"request-handlers",
"og_databases", "og_databases",
"sentry", "sentry",
] ]

View File

@ -0,0 +1,11 @@
// <setup>
use actix_web::{web, App, HttpRequest, Responder};
fn index(_req: HttpRequest) -> impl Responder {
"Hello world!"
}
pub fn main() {
App::new().service(web::scope("/app").route("/index.html", web::get().to(index)));
}
// </setup>

View File

@ -0,0 +1,25 @@
use actix_web::{web, App, HttpResponse, HttpServer};
// <combine>
struct State1;
struct State2;
#[rustfmt::skip]
pub fn main() {
HttpServer::new(|| {
App::new()
.data(State1)
.data(State2)
.service(
web::scope("/app1")
.route("/", web::to(|| HttpResponse::Ok())))
.service(
web::scope("/app2")
.route("/", web::to(|| HttpResponse::Ok())))
})
.bind("127.0.0.1:8088")
.unwrap()
.run()
.unwrap();
}
// </combine>

View File

@ -1,37 +1,22 @@
#![allow(unused_variables)] use actix_web::{web, App, HttpResponse, HttpServer};
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer, Responder};
mod state; pub mod app;
mod vh; pub mod combine;
pub mod state;
pub mod vh;
#[rustfmt::skip] #[rustfmt::skip]
fn make_app() {
// <make_app>
fn index(_req: HttpRequest) -> impl Responder {
"Hello world!"
}
let app = App::new()
.service(web::scope("/app").route("/index.html", web::get().to(index)));
// </make_app>
}
#[rustfmt::skip]
fn run_server() {
// <run_server> // <run_server>
let server = HttpServer::new(|| {
App::new()
.service(web::scope("/app1").route("/", web::to(|| HttpResponse::Ok())))
.service(web::scope("/app2").route("/", web::to(|| HttpResponse::Ok())))
.route("/", web::to(|| HttpResponse::Ok()))
});
// </run_server>
}
fn main() { fn main() {
make_app(); HttpServer::new(|| {
run_server(); App::new()
state::test(); .service(
web::scope("/app1")
.route("/", web::to(|| HttpResponse::Ok())))
.service(
web::scope("/app2")
.route("/", web::to(|| HttpResponse::Ok())))
.route("/", web::to(|| HttpResponse::Ok()))
});
} }
// </run_server>

View File

@ -1,6 +1,5 @@
#![allow(dead_code, unused)]
// <setup> // <setup>
use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer}; use actix_web::{web, App, HttpServer};
use std::cell::Cell; use std::cell::Cell;
// This struct represents state // This struct represents state
@ -16,63 +15,28 @@ fn index(data: web::Data<AppState>) -> String {
} }
// </setup> // </setup>
#[rustfmt::skip]
fn make_app() {
// <make_app> // <make_app>
App::new() fn _main() {
.data( AppState { counter: Cell::new(0) })
.route("/", web::get().to(index));
// </make_app>
}
#[rustfmt::skip]
fn start_app() {
// <start_app>
HttpServer::new(|| {
App::new() App::new()
.data( AppState { counter: Cell::new(0) }) .data(AppState {
.route("/", web::get().to(index)) counter: Cell::new(0),
}) })
.bind("127.0.0.1:8088") .route("/", web::get().to(index));
.unwrap()
.run()
.unwrap();
// </start_app>
} }
// </make_app>
use std::thread; // <start_app>
pub fn main() {
#[rustfmt::skip]
fn combine() {
thread::spawn(|| {
// <combine>
struct State1;
struct State2;
fn main() {
HttpServer::new(|| { HttpServer::new(|| {
App::new() App::new()
.data(State1) .data(AppState {
.data(State2) counter: Cell::new(0),
.service( })
web::scope("/app1") .route("/", web::get().to(index))
.route("/", web::to(|| HttpResponse::Ok())),
)
.service(
web::scope("/app2")
.route("/", web::to(|| HttpResponse::Ok())),
)
}) })
.bind("127.0.0.1:8088") .bind("127.0.0.1:8088")
.unwrap() .unwrap()
.run() .run()
.unwrap(); .unwrap();
} }
// </combine> // </start_app>
});
}
pub fn test() {
make_app();
combine();
}

View File

@ -1,3 +1,4 @@
use actix_web::{web, App};
// <helpers> // <helpers>
use actix_web::{error, HttpRequest, Result}; use actix_web::{error, HttpRequest, Result};
@ -6,9 +7,12 @@ struct MyError {
name: &'static str, name: &'static str,
} }
fn index(req: &HttpRequest) -> Result<&'static str> { pub fn index(_req: HttpRequest) -> Result<&'static str> {
let result: Result<&'static str, MyError> = Err(MyError { name: "test" }); let result: Result<&'static str, MyError> = Err(MyError { name: "test" });
Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?) Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?)
} }
// </helpers> // </helpers>
pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -1,21 +1,24 @@
mod helpers; pub mod helpers;
mod override_error; pub mod override_error;
mod recommend_one; pub mod recommend_one;
use actix_web::{web, App};
// <response-error> // <response-error>
use actix_web::{error, HttpRequest}; use actix_web::{error, HttpRequest};
use failure::Fail; use failure::Fail;
#[derive(Fail, Debug)] #[derive(Fail, Debug)]
#[fail(display = "my error")] #[fail(display = "my error")]
struct MyError { pub struct MyError {
name: &'static str, name: &'static str,
} }
// Use default implementation for `error_response()` method // Use default implementation for `error_response()` method
impl error::ResponseError for MyError {} impl error::ResponseError for MyError {}
fn index(req: HttpRequest) -> Result<&'static str, MyError> { fn index(_req: HttpRequest) -> Result<&'static str, MyError> {
Err(MyError { name: "test" }) Err(MyError { name: "test" })
} }
// </response-error> // </response-error>
fn main() {} pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -1,3 +1,4 @@
use actix_web::{web, App};
// <override> // <override>
use actix_web::{error, http, HttpRequest, HttpResponse}; use actix_web::{error, http, HttpRequest, HttpResponse};
use failure::Fail; use failure::Fail;
@ -24,7 +25,21 @@ impl error::ResponseError for MyError {
} }
} }
fn index(req: &HttpRequest) -> Result<&'static str, MyError> { fn index(_req: HttpRequest) -> Result<&'static str, MyError> {
Err(MyError::BadClientData) Err(MyError::BadClientData)
} }
// </override> // </override>
pub fn main() {
App::new()
.route("/", web::get().to(index))
.route("/e2", web::get().to(error2))
.route("/e3", web::get().to(error3));
}
fn error2(_req: HttpRequest) -> Result<&'static str, MyError> {
Err(MyError::InternalError)
}
fn error3(_req: HttpRequest) -> Result<&'static str, MyError> {
Err(MyError::Timeout)
}

View File

@ -1,3 +1,4 @@
use actix_web::{web, App, HttpRequest};
// <recommend-one> // <recommend-one>
use actix_web::{error, http, HttpResponse}; use actix_web::{error, http, HttpResponse};
use failure::Fail; use failure::Fail;
@ -18,3 +19,12 @@ impl error::ResponseError for UserError {
} }
} }
// </recommend-one> // </recommend-one>
pub fn main() {
App::new().route("/", web::get().to(index));
}
fn index(_req: HttpRequest) -> Result<&'static str, UserError> {
Err(UserError::ValidationError {
field: "bad stuff".to_string(),
})
}

View File

@ -1,5 +1,6 @@
use actix_web::App;
// <recommend-two> // <recommend-two>
use actix_web::{error, fs, http, App, HttpRequest, HttpResponse}; use actix_web::{error, fs, http, HttpRequest, HttpResponse};
use failure::Fail; use failure::Fail;
#[derive(Fail, Debug)] #[derive(Fail, Debug)]
@ -23,3 +24,6 @@ fn index(_req: HttpRequest) -> Result<&'static str, UserError> {
Ok("success!") Ok("success!")
} }
// </recommend-two> // </recommend-two>
pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -2,14 +2,14 @@ use actix_web::{web, App, FromRequest, HttpRequest, HttpServer, Responder};
use futures::future::Future; use futures::future::Future;
use serde::Deserialize; use serde::Deserialize;
// mod custom_handler; // pub mod custom_handler;
mod form; pub mod form;
mod json_one; pub mod json_one;
mod json_two; pub mod json_two;
mod multiple; pub mod multiple;
mod path_one; pub mod path_one;
mod path_two; pub mod path_two;
mod query; pub mod query;
#[derive(Deserialize, Debug)] #[derive(Deserialize, Debug)]
struct MyInfo { struct MyInfo {

View File

@ -10,7 +10,7 @@ struct Info {
/// extract path info using serde /// extract path info using serde
fn index(info: web::Path<Info>) -> Result<String> { fn index(info: web::Path<Info>) -> Result<String> {
Ok(format!("Welcome {}!", info.friend)) Ok(format!("Welcome {}, userid {}!", info.friend, info.userid))
} }
pub fn main() { pub fn main() {

View File

@ -1,7 +1,7 @@
// <default-headers> // <default-headers>
use actix_web::{http, middleware, web, App, HttpResponse}; use actix_web::{http, middleware, web, App, HttpResponse};
fn main() { pub fn main() {
App::new() App::new()
.wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2")) .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
.service( .service(

View File

@ -10,7 +10,7 @@ fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerRespons
Ok(ErrorHandlerResponse::Response(res)) Ok(ErrorHandlerResponse::Response(res))
} }
fn main() { pub fn main() {
App::new() App::new()
.wrap( .wrap(
ErrorHandlers::new() ErrorHandlers::new()

View File

@ -3,7 +3,7 @@ use actix_web::middleware::Logger;
use actix_web::App; use actix_web::App;
use env_logger; use env_logger;
fn main() { pub fn main() {
std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();

View File

@ -1,7 +1,7 @@
mod default_headers; pub mod default_headers;
mod errorhandler; pub mod errorhandler;
mod logger; pub mod logger;
mod user_sessions; pub mod user_sessions;
// <main> // <main>
use actix_service::{Service, Transform}; use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, web, App, Error}; use actix_web::{dev::ServiceRequest, dev::ServiceResponse, web, App, Error};

View File

@ -19,7 +19,7 @@ fn index(session: Session, req: HttpRequest) -> Result<&'static str> {
Ok("welcome!") Ok("welcome!")
} }
fn main() -> std::io::Result<()> { pub fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info"); std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init(); env_logger::init();

View File

@ -9,7 +9,7 @@
// number: i32, // number: i32,
// } // }
// fn index(req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> { // pub fn index(req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
// req.json() // req.json()
// .from_err() // .from_err()
// .and_then(|val: MyObj| { // .and_then(|val: MyObj| {

View File

@ -1,8 +1,8 @@
mod json_two; pub mod json_two;
mod manual; pub mod manual;
mod multipart; pub mod multipart;
mod streaming; pub mod streaming;
mod urlencoded; pub mod urlencoded;
// <json-request> // <json-request>
use actix_web::{web, App, Result}; use actix_web::{web, App, Result};
use serde::Deserialize; use serde::Deserialize;

View File

@ -1,5 +1,5 @@
// <json-manual> // <json-manual>
use actix_web::{error, web, Error, HttpResponse}; use actix_web::{error, web, App, Error, HttpResponse};
use bytes::BytesMut; use bytes::BytesMut;
use futures::{Future, Stream}; use futures::{Future, Stream};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -13,7 +13,7 @@ struct MyObj {
const MAX_SIZE: usize = 262_144; // max payload size is 256k const MAX_SIZE: usize = 262_144; // max payload size is 256k
fn index_manual( pub fn index_manual(
payload: web::Payload, payload: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> { ) -> impl Future<Item = HttpResponse, Error = Error> {
// payload is a stream of Bytes objects // payload is a stream of Bytes objects
@ -41,3 +41,7 @@ fn index_manual(
}) })
} }
// </json-manual> // </json-manual>
pub fn main() {
App::new().route("/", web::post().to_async(index_manual));
}

View File

@ -2,7 +2,7 @@
// use actix_web::{error, Error, HttpRequest, HttpResponse}; // use actix_web::{error, Error, HttpRequest, HttpResponse};
// use futures::Future; // use futures::Future;
// fn index(req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> { // pub fn index(req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
// // get multipart and iterate over multipart items // // get multipart and iterate over multipart items
// req.multipart().and_then(|item| match item { // req.multipart().and_then(|item| match item {
// multipart::MultipartItem::Field(field) => { // multipart::MultipartItem::Field(field) => {

View File

@ -2,7 +2,7 @@
// use actix_web::{error, web, Error, HttpResponse}; // use actix_web::{error, web, Error, HttpResponse};
// use futures::{future::result, Future, Stream}; // use futures::{future::result, Future, Stream};
// fn index(payload: web::Payload) -> Box<Future<Item = HttpResponse, Error = Error>> { // pub fn index(payload: web::Payload) -> Box<Future<Item = HttpResponse, Error = Error>> {
// payload // payload
// .from_err() // .from_err()
// .fold((), |_, chunk| { // .fold((), |_, chunk| {

View File

@ -19,4 +19,4 @@
// .responder() // .responder()
// } // }
// </urlencoded> // </urlencoded>
fn main() {} pub fn main() {}

View File

@ -3,12 +3,12 @@ use actix_web::{
http::ContentEncoding, middleware, web, App, HttpRequest, HttpResponse, http::ContentEncoding, middleware, web, App, HttpRequest, HttpResponse,
}; };
fn index(req: HttpRequest) -> HttpResponse { fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::Ok().body("data") HttpResponse::Ok().body("data")
} }
fn main() { pub fn main() {
let app = App::new() App::new()
// v- disable compression for all routes // v- disable compression for all routes
.wrap(middleware::Compress::new(ContentEncoding::Identity)) .wrap(middleware::Compress::new(ContentEncoding::Identity))
.route("/", web::get().to(index)); .route("/", web::get().to(index));

View File

@ -3,11 +3,14 @@ use actix_web::{
http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse, http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse,
}; };
fn index_br(req: HttpRequest) -> HttpResponse { fn index_br(_req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.encoding(ContentEncoding::Br) .encoding(ContentEncoding::Br)
.body("data") .body("data")
} }
// </brotli> // </brotli>
fn main() {} use actix_web::{web, App};
pub fn main() {
App::new().route("/", web::get().to(index_br));
}

View File

@ -11,4 +11,4 @@
// )))))) // ))))))
// } // }
// </chunked> // </chunked>
fn main() {} pub fn main() {}

View File

@ -3,10 +3,15 @@ use actix_web::{
http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse, http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse,
}; };
fn index(req: HttpRequest) -> HttpResponse { fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
// v- disable compression // v- disable compression
.encoding(ContentEncoding::Identity) .encoding(ContentEncoding::Identity)
.body("data") .body("data")
} }
// </identity> // </identity>
use actix_web::{web, App};
pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -16,3 +16,8 @@ pub fn index(_req: HttpRequest) -> HttpResponse {
.body(HELLO_WORLD) .body(HELLO_WORLD)
} }
// </identity-two> // </identity-two>
use actix_web::{web, App};
pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -13,7 +13,7 @@ fn index(req: HttpRequest) -> Result<web::Json<MyObj>> {
})) }))
} }
fn main() { pub fn main() {
App::new().route(r"/a/{name}", web::get().to(index)); App::new().route(r"/a/{name}", web::get().to(index));
} }
// </json-resp> // </json-resp>

View File

@ -1,9 +1,9 @@
mod auto; pub mod auto;
mod brotli; pub mod brotli;
mod chunked; pub mod chunked;
mod identity; pub mod identity;
mod identity_two; pub mod identity_two;
mod json_resp; pub mod json_resp;
// <builder> // <builder>
use actix_web::{ use actix_web::{
http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse, http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse,
@ -18,4 +18,7 @@ fn index(_req: HttpRequest) -> HttpResponse {
} }
// </builder> // </builder>
fn main() {} use actix_web::{web, App};
pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -1,7 +1,7 @@
// <keep-alive> // <keep-alive>
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};
fn main() { pub fn main() {
HttpServer::new(|| { HttpServer::new(|| {
App::new().route("/", web::get().to(|| HttpResponse::Ok())) App::new().route("/", web::get().to(|| HttpResponse::Ok()))
}) })

View File

@ -1,7 +1,7 @@
// <example> // <example>
use actix_web::{http, HttpRequest, HttpResponse}; use actix_web::{http, HttpRequest, HttpResponse};
fn index(req: HttpRequest) -> HttpResponse { pub fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
.connection_type(http::ConnectionType::Close) // <- Close connection .connection_type(http::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method .force_close() // <- Alternative method

View File

@ -1,8 +1,8 @@
// mod keep_alive; // pub mod keep_alive;
// mod keep_alive_tp; // pub mod keep_alive_tp;
mod signals; pub mod signals;
mod ssl; pub mod ssl;
mod workers; pub mod workers;
// <main> // <main>
use actix_web::{web, App, HttpResponse, HttpServer}; use actix_web::{web, App, HttpResponse, HttpServer};

View File

@ -2,7 +2,7 @@
use actix_files as fs; use actix_files as fs;
use actix_web::App; use actix_web::App;
fn main() { pub fn main() {
App::new().service(fs::Files::new("/static", ".").show_files_listing()); App::new().service(fs::Files::new("/static", ".").show_files_listing());
} }
// </directory> // </directory>

View File

@ -1,6 +1,6 @@
mod configuration; pub mod configuration;
mod configuration_two; pub mod configuration_two;
mod directory; pub mod directory;
// <individual-file> // <individual-file>
use actix_files::NamedFile; use actix_files::NamedFile;
use actix_web::{web, App, HttpRequest, Result}; use actix_web::{web, App, HttpRequest, Result};

View File

@ -5,7 +5,7 @@ fn index(_req: HttpRequest) -> impl Responder {
} }
// <default> // <default>
fn main() { pub fn main() {
App::new() App::new()
.service(web::resource("/").route(web::get().to(index))) .service(web::resource("/").route(web::get().to(index)))
.default_service( .default_service(

View File

@ -1,17 +1,17 @@
mod cfg; pub mod cfg;
mod dhandler; pub mod dhandler;
mod minfo; pub mod minfo;
mod norm; pub mod norm;
mod norm2; pub mod norm2;
mod path; pub mod path;
mod path2; pub mod path2;
mod pbuf; pub mod pbuf;
mod pred; pub mod pred;
mod pred2; pub mod pred2;
mod resource; pub mod resource;
mod scope; pub mod scope;
mod url_ext; pub mod url_ext;
mod urls; pub mod urls;
// <main> // <main>
use actix_web::{web, App, HttpRequest, HttpResponse}; use actix_web::{web, App, HttpRequest, HttpResponse};

View File

@ -1,5 +1,5 @@
// <minfo> // <minfo>
use actix_web::{web, App, HttpRequest, HttpServer, Result}; use actix_web::{web, App, HttpRequest, Result};
fn index(req: HttpRequest) -> Result<String> { fn index(req: HttpRequest) -> Result<String> {
let v1: u8 = req.match_info().get("v1").unwrap().parse().unwrap(); let v1: u8 = req.match_info().get("v1").unwrap().parse().unwrap();
@ -8,7 +8,7 @@ fn index(req: HttpRequest) -> Result<String> {
Ok(format!("Values {} {} {} {}", v1, v2, v3, v4)) Ok(format!("Values {} {} {} {}", v1, v2, v3, v4))
} }
fn main() { pub fn main() {
App::new() App::new()
.route("/a/{v1}/{v2}/", web::get().to(index)) .route("/a/{v1}/{v2}/", web::get().to(index))
.route("", web::get().to(|| actix_web::HttpResponse::Ok())); .route("", web::get().to(|| actix_web::HttpResponse::Ok()));

View File

@ -1,10 +1,10 @@
// <norm> // <norm>
use actix_web::{middleware, web, App, HttpResponse}; use actix_web::{middleware, web, App};
fn main() { pub fn main() {
App::new() App::new()
.wrap(middleware::NormalizePath) .wrap(middleware::NormalizePath)
.route("/", web::get().to(|| HttpResponse::Ok())); .route("/", web::get().to(index));
} }
// </norm> // </norm>

View File

@ -1,7 +1,7 @@
// <norm> // <norm>
use actix_web::{http::Method, middleware, web, App}; use actix_web::{http::Method, middleware, web, App};
fn main() { pub fn main() {
App::new() App::new()
.wrap(middleware::NormalizePath) .wrap(middleware::NormalizePath)
.route("/resource/", web::get().to(index)) .route("/resource/", web::get().to(index))

View File

@ -6,7 +6,7 @@ fn index(info: web::Path<(String, u32)>) -> Result<String> {
Ok(format!("Welcome {}! id: {}", info.0, info.1)) Ok(format!("Welcome {}! id: {}", info.0, info.1))
} }
fn main() { pub fn main() {
App::new().route( App::new().route(
"/{username}/{id}/index.html", // <- define path parameters "/{username}/{id}/index.html", // <- define path parameters
web::get().to(index), web::get().to(index),

View File

@ -7,7 +7,7 @@ fn index(req: HttpRequest) -> Result<String> {
Ok(format!("Path {:?}", path)) Ok(format!("Path {:?}", path))
} }
fn main() { pub fn main() {
App::new().route(r"/a/{tail:.*}", web::get().to(index)); App::new().route(r"/a/{tail:.*}", web::get().to(index));
} }
// </pbuf> // </pbuf>

View File

@ -9,7 +9,7 @@ impl Guard for ContentTypeHeader {
} }
} }
fn main() { pub fn main() {
App::new().route( App::new().route(
"", "",
web::route() web::route()

View File

@ -1,7 +1,7 @@
// <pred> // <pred>
use actix_web::{guard, web, App, HttpResponse}; use actix_web::{guard, web, App, HttpResponse};
fn main() { pub fn main() {
App::new().route( App::new().route(
"/", "/",
web::route() web::route()

View File

@ -1,11 +1,11 @@
// <resource> // <resource>
use actix_web::{http::Method, web, App, HttpRequest, HttpResponse}; use actix_web::{web, App, HttpRequest, HttpResponse};
fn index(_req: HttpRequest) -> HttpResponse { fn index(_req: HttpRequest) -> HttpResponse {
unimplemented!() unimplemented!()
} }
fn main() { pub fn main() {
App::new() App::new()
.service(web::resource("/prefix").to(index)) .service(web::resource("/prefix").to(index))
.service( .service(

View File

@ -5,10 +5,7 @@ fn show_users(_req: HttpRequest) -> HttpResponse {
unimplemented!() unimplemented!()
} }
#[rustfmt::skip] pub fn main() {
fn main() { App::new().service(web::scope("/users").route("/show", web::get().to(show_users)));
App::new()
.service(web::scope("/users")
.route("/show", web::get().to(show_users)));
} }
// </scope> // </scope>

View File

@ -1,5 +1,5 @@
// <ext> // <ext>
use actix_web::{web, App, Error, HttpRequest, HttpResponse, Responder}; use actix_web::{web, App, HttpRequest, Responder};
fn index(req: HttpRequest) -> impl Responder { fn index(req: HttpRequest) -> impl Responder {
let url = req.url_for("youtube", &["oHg5SJYRHA0"]).unwrap(); let url = req.url_for("youtube", &["oHg5SJYRHA0"]).unwrap();

View File

@ -1,7 +1,5 @@
// <url> // <url>
use actix_web::{ use actix_web::{guard, http::header, web, App, HttpRequest, HttpResponse, Result};
guard, http::header, http::Method, web, App, HttpRequest, HttpResponse, Result,
};
fn index(req: HttpRequest) -> Result<HttpResponse> { fn index(req: HttpRequest) -> Result<HttpResponse> {
let url = req.url_for("foo", &["1", "2", "3"])?; // <- generate url for "foo" resource let url = req.url_for("foo", &["1", "2", "3"])?; // <- generate url for "foo" resource