1
0
mirror of https://github.com/actix/actix-website synced 2024-11-23 16:31:08 +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;
> 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
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:
{{< 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.
**Applications get matched based on registration order**. If an application with a more generic
@ -61,8 +61,7 @@ When the app is initialized it needs to be passed the initial state:
> instance. Http server constructs an application instance for each thread, thus application state
> 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`,
> 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:
@ -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.
{{< 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

View File

@ -11,20 +11,20 @@ members = [
"url-dispatch",
"responder-trait",
"either",
]
exclude = [
"request-handlers",
"async-handlers",
"extractors",
"autoreload",
"errors",
"requests",
"responses",
"testing",
"middleware",
"static-files",
"websockets",
"http2",
]
exclude = [
"testing",
"async-handlers",
"websockets",
"request-handlers",
"og_databases",
"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, HttpRequest, HttpResponse, HttpServer, Responder};
use actix_web::{web, App, HttpResponse, HttpServer};
mod state;
mod vh;
pub mod app;
pub mod combine;
pub mod state;
pub mod vh;
#[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>
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() {
make_app();
run_server();
state::test();
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>

View File

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

View File

@ -1,3 +1,4 @@
use actix_web::{web, App};
// <helpers>
use actix_web::{error, HttpRequest, Result};
@ -6,9 +7,12 @@ struct MyError {
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" });
Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?)
}
// </helpers>
pub fn main() {
App::new().route("/", web::get().to(index));
}

View File

@ -1,21 +1,24 @@
mod helpers;
mod override_error;
mod recommend_one;
pub mod helpers;
pub mod override_error;
pub mod recommend_one;
use actix_web::{web, App};
// <response-error>
use actix_web::{error, HttpRequest};
use failure::Fail;
#[derive(Fail, Debug)]
#[fail(display = "my error")]
struct MyError {
pub struct MyError {
name: &'static str,
}
// Use default implementation for `error_response()` method
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" })
}
// </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>
use actix_web::{error, http, HttpRequest, HttpResponse};
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)
}
// </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>
use actix_web::{error, http, HttpResponse};
use failure::Fail;
@ -18,3 +19,12 @@ impl error::ResponseError for UserError {
}
}
// </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>
use actix_web::{error, fs, http, App, HttpRequest, HttpResponse};
use actix_web::{error, fs, http, HttpRequest, HttpResponse};
use failure::Fail;
#[derive(Fail, Debug)]
@ -23,3 +24,6 @@ fn index(_req: HttpRequest) -> Result<&'static str, UserError> {
Ok("success!")
}
// </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 serde::Deserialize;
// mod custom_handler;
mod form;
mod json_one;
mod json_two;
mod multiple;
mod path_one;
mod path_two;
mod query;
// pub mod custom_handler;
pub mod form;
pub mod json_one;
pub mod json_two;
pub mod multiple;
pub mod path_one;
pub mod path_two;
pub mod query;
#[derive(Deserialize, Debug)]
struct MyInfo {

View File

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

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
mod default_headers;
mod errorhandler;
mod logger;
mod user_sessions;
pub mod default_headers;
pub mod errorhandler;
pub mod logger;
pub mod user_sessions;
// <main>
use actix_service::{Service, Transform};
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!")
}
fn main() -> std::io::Result<()> {
pub fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();

View File

@ -9,7 +9,7 @@
// 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()
// .from_err()
// .and_then(|val: MyObj| {

View File

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

View File

@ -1,5 +1,5 @@
// <json-manual>
use actix_web::{error, web, Error, HttpResponse};
use actix_web::{error, web, App, Error, HttpResponse};
use bytes::BytesMut;
use futures::{Future, Stream};
use serde::{Deserialize, Serialize};
@ -13,7 +13,7 @@ struct MyObj {
const MAX_SIZE: usize = 262_144; // max payload size is 256k
fn index_manual(
pub fn index_manual(
payload: web::Payload,
) -> impl Future<Item = HttpResponse, Error = Error> {
// payload is a stream of Bytes objects
@ -41,3 +41,7 @@ fn index_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 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
// req.multipart().and_then(|item| match item {
// multipart::MultipartItem::Field(field) => {

View File

@ -2,7 +2,7 @@
// use actix_web::{error, web, Error, HttpResponse};
// 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
// .from_err()
// .fold((), |_, chunk| {

View File

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

View File

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

View File

@ -3,11 +3,14 @@ use actix_web::{
http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse,
};
fn index_br(req: HttpRequest) -> HttpResponse {
fn index_br(_req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
.encoding(ContentEncoding::Br)
.body("data")
}
// </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>
fn main() {}
pub fn main() {}

View File

@ -3,10 +3,15 @@ use actix_web::{
http::ContentEncoding, middleware::BodyEncoding, HttpRequest, HttpResponse,
};
fn index(req: HttpRequest) -> HttpResponse {
fn index(_req: HttpRequest) -> HttpResponse {
HttpResponse::Ok()
// v- disable compression
.encoding(ContentEncoding::Identity)
.body("data")
}
// </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)
}
// </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));
}
// </json-resp>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,5 +1,5 @@
// <minfo>
use actix_web::{web, App, HttpRequest, HttpServer, Result};
use actix_web::{web, App, HttpRequest, Result};
fn index(req: HttpRequest) -> Result<String> {
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))
}
fn main() {
pub fn main() {
App::new()
.route("/a/{v1}/{v2}/", web::get().to(index))
.route("", web::get().to(|| actix_web::HttpResponse::Ok()));

View File

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

View File

@ -1,7 +1,7 @@
// <norm>
use actix_web::{http::Method, middleware, web, App};
fn main() {
pub fn main() {
App::new()
.wrap(middleware::NormalizePath)
.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))
}
fn main() {
pub fn main() {
App::new().route(
"/{username}/{id}/index.html", // <- define path parameters
web::get().to(index),

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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