mirror of
https://github.com/actix/examples
synced 2025-06-27 01:27:43 +02:00
Restructure folders (#411)
This commit is contained in:
committed by
GitHub
parent
9db98162b2
commit
c3407627d0
12
basics/basics/Cargo.toml
Normal file
12
basics/basics/Cargo.toml
Normal file
@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "basics"
|
||||
version = "2.0.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
actix-web = "3"
|
||||
actix-files = "0.3"
|
||||
actix-session = "0.4"
|
||||
actix-utils = "2"
|
||||
env_logger = "0.8"
|
22
basics/basics/README.md
Normal file
22
basics/basics/README.md
Normal file
@ -0,0 +1,22 @@
|
||||
# basics
|
||||
|
||||
## Usage
|
||||
|
||||
### server
|
||||
|
||||
```bash
|
||||
cd examples/basics
|
||||
cargo run
|
||||
# Started http server: 127.0.0.1:8080
|
||||
```
|
||||
|
||||
### web client
|
||||
|
||||
- [http://localhost:8080/](http://localhost:8080/static/index.html)
|
||||
- [http://localhost:8080/async-body/bob](http://localhost:8080/async-body/bob)
|
||||
- [http://localhost:8080/user/bob/](http://localhost:8080/user/bob/) text/plain download
|
||||
- [http://localhost:8080/test](http://localhost:8080/test) (return status switch GET or POST or other)
|
||||
- [http://localhost:8080/favicon](http://localhost:8080/favicon)
|
||||
- [http://localhost:8080/welcome](http://localhost:8080/static/welcome.html)
|
||||
- [http://localhost:8080/notexit](http://localhost:8080/static/404.html) display 404 page
|
||||
- [http://localhost:8080/error](http://localhost:8080/error) Panic after request
|
124
basics/basics/src/main.rs
Normal file
124
basics/basics/src/main.rs
Normal file
@ -0,0 +1,124 @@
|
||||
use actix_files as fs;
|
||||
use actix_session::{CookieSession, Session};
|
||||
use actix_utils::mpsc;
|
||||
use actix_web::http::{header, Method, StatusCode};
|
||||
use actix_web::{
|
||||
error, get, guard, middleware, web, App, Error, HttpRequest, HttpResponse,
|
||||
HttpServer, Result,
|
||||
};
|
||||
use std::{env, io};
|
||||
|
||||
/// favicon handler
|
||||
#[get("/favicon")]
|
||||
async fn favicon() -> Result<fs::NamedFile> {
|
||||
Ok(fs::NamedFile::open("static/favicon.ico")?)
|
||||
}
|
||||
|
||||
/// simple index handler
|
||||
#[get("/welcome")]
|
||||
async fn welcome(session: Session, req: HttpRequest) -> 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.set("counter", counter)?;
|
||||
|
||||
// response
|
||||
Ok(HttpResponse::build(StatusCode::OK)
|
||||
.content_type("text/html; charset=utf-8")
|
||||
.body(include_str!("../static/welcome.html")))
|
||||
}
|
||||
|
||||
/// 404 handler
|
||||
async fn p404() -> Result<fs::NamedFile> {
|
||||
Ok(fs::NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND))
|
||||
}
|
||||
|
||||
/// response body
|
||||
async fn response_body(path: web::Path<String>) -> HttpResponse {
|
||||
let text = format!("Hello {}!", *path);
|
||||
|
||||
let (tx, rx_body) = mpsc::channel();
|
||||
let _ = tx.send(Ok::<_, Error>(web::Bytes::from(text)));
|
||||
|
||||
HttpResponse::Ok().streaming(rx_body)
|
||||
}
|
||||
|
||||
/// handler with path parameters like `/user/{name}/`
|
||||
async fn with_param(
|
||||
req: HttpRequest,
|
||||
web::Path((name,)): web::Path<(String,)>,
|
||||
) -> HttpResponse {
|
||||
println!("{:?}", req);
|
||||
|
||||
HttpResponse::Ok()
|
||||
.content_type("text/plain")
|
||||
.body(format!("Hello {}!", name))
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> io::Result<()> {
|
||||
env::set_var("RUST_LOG", "actix_web=debug,actix_server=info");
|
||||
env_logger::init();
|
||||
|
||||
HttpServer::new(|| {
|
||||
App::new()
|
||||
// cookie session middleware
|
||||
.wrap(CookieSession::signed(&[0; 32]).secure(false))
|
||||
// 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().to(response_body)),
|
||||
)
|
||||
.service(
|
||||
web::resource("/test").to(|req: HttpRequest| match *req.method() {
|
||||
Method::GET => HttpResponse::Ok(),
|
||||
Method::POST => HttpResponse::MethodNotAllowed(),
|
||||
_ => HttpResponse::NotFound(),
|
||||
}),
|
||||
)
|
||||
.service(web::resource("/error").to(|| async {
|
||||
error::InternalError::new(
|
||||
io::Error::new(io::ErrorKind::Other, "test"),
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
)
|
||||
}))
|
||||
// static files
|
||||
.service(fs::Files::new("/static", "static").show_files_listing())
|
||||
// redirect
|
||||
.service(web::resource("/").route(web::get().to(|req: HttpRequest| {
|
||||
println!("{:?}", req);
|
||||
HttpResponse::Found()
|
||||
.header(header::LOCATION, "static/welcome.html")
|
||||
.finish()
|
||||
})))
|
||||
// default
|
||||
.default_service(
|
||||
// 404 for GET request
|
||||
web::resource("")
|
||||
.route(web::get().to(p404))
|
||||
// all requests that are not `GET`
|
||||
.route(
|
||||
web::route()
|
||||
.guard(guard::Not(guard::Get()))
|
||||
.to(HttpResponse::MethodNotAllowed),
|
||||
),
|
||||
)
|
||||
})
|
||||
.bind("127.0.0.1:8080")?
|
||||
.run()
|
||||
.await
|
||||
}
|
14
basics/basics/static/404.html
Normal file
14
basics/basics/static/404.html
Normal file
@ -0,0 +1,14 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>actix - basics</title>
|
||||
<link rel="shortcut icon" type="image/x-icon" href="/favicon">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<a href="/static/welcome.html">back to home</a>
|
||||
<h1>404</h1>
|
||||
</body>
|
||||
|
||||
</html>
|
BIN
basics/basics/static/actixLogo.png
Normal file
BIN
basics/basics/static/actixLogo.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 13 KiB |
BIN
basics/basics/static/favicon.ico
Normal file
BIN
basics/basics/static/favicon.ico
Normal file
Binary file not shown.
After Width: | Height: | Size: 32 KiB |
13
basics/basics/static/welcome.html
Normal file
13
basics/basics/static/welcome.html
Normal file
@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
|
||||
<head>
|
||||
<title>actix - basics</title>
|
||||
<link rel="shortcut icon" type="image/x-icon" href="/favicon">
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<h1>Welcome <img width="30" height="30" src="/static/actixLogo.png"></h1>
|
||||
</body>
|
||||
|
||||
</html>
|
Reference in New Issue
Block a user