Skip to content

Commit

Permalink
standardize examples
Browse files Browse the repository at this point in the history
  • Loading branch information
robjtede committed Mar 14, 2023
1 parent ca6eaee commit 6424e4e
Show file tree
Hide file tree
Showing 30 changed files with 168 additions and 394 deletions.
385 changes: 73 additions & 312 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ members = [
"basics/nested-routing",
"basics/state",
"basics/static-files",
"basics/todo",
# "basics/todo",
"cors/backend",
"data-factory",
"databases/diesel",
Expand Down
5 changes: 3 additions & 2 deletions auth/casbin/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ edition = "2021"

[dependencies]
actix-web.workspace = true

casbin = "2"
loge = { version = "0.4", default-features = false, features = ["colored", "chrono"] }
tokio = { workspace = true, features = ["sync"] }
env_logger.workspace = true
tokio.workspace = true
5 changes: 1 addition & 4 deletions auth/casbin/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,7 @@ async fn fail(enforcer: web::Data<RwLock<Enforcer>>, req: HttpRequest) -> HttpRe

#[actix_web::main]
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "info");
std::env::set_var("LOGE_FORMAT", "target");

loge::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

let model = DefaultModel::from_file("rbac/rbac_model.conf")
.await
Expand Down
6 changes: 3 additions & 3 deletions auth/cookie-session/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@ async fn index(session: Session, req: HttpRequest) -> Result<&'static str> {

#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "info");
env_logger::init();
log::info!("Starting http server: 127.0.0.1:8080");
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

log::info!("starting HTTP server at http://localhost:8080");

HttpServer::new(|| {
App::new()
Expand Down
7 changes: 4 additions & 3 deletions auth/simple-auth-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,21 @@ version = "1.0.0"
edition = "2021"

[dependencies]
actix-web.workspace = true
actix-identity.workspace = true
actix-session = { workspace = true, features = ["cookie-session"] }
actix-web.workspace = true

chrono = { version = "0.4.20", features = ["serde"] }
derive_more.workspace = true
diesel = { version = "2", features = ["postgres", "r2d2", "uuid", "chrono"] }
dotenv = "0.15"
env_logger.workspace = true
log = "0.4"
once_cell = "1"
r2d2 = "0.8"
rust-argon2 = "1"
serde.workspace = true
serde_json.workspace = true
serde.workspace = true
sparkpost = "0.5"
uuid = { version = "1", features = ["v4", "serde"] }
time = "0.3"
uuid = { version = "1", features = ["v4", "serde"] }
17 changes: 6 additions & 11 deletions auth/simple-auth-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ extern crate diesel;
use actix_identity::IdentityMiddleware;
use actix_session::{config::PersistentSession, storage::CookieSessionStore, SessionMiddleware};
use actix_web::{cookie::Key, middleware, web, App, HttpServer};
use diesel::{
prelude::*,
r2d2::{self, ConnectionManager},
};
use diesel::{prelude::*, r2d2};
use time::Duration;

mod auth_handler;
Expand All @@ -22,21 +19,19 @@ mod utils;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenv::dotenv().ok();
std::env::set_var(
"RUST_LOG",
"simple-auth-server=debug,actix_web=info,actix_server=info",
);
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");

// create db connection pool
let manager = ConnectionManager::<PgConnection>::new(database_url);
let manager = r2d2::ConnectionManager::<PgConnection>::new(database_url);
let pool: models::Pool = r2d2::Pool::builder()
.build(manager)
.expect("Failed to create pool.");
let domain: String = std::env::var("DOMAIN").unwrap_or_else(|_| "localhost".to_string());

// Start http server
log::info!("starting HTTP server at http://localhost:8080");

HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
Expand Down
1 change: 1 addition & 0 deletions basics/hello-world/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
[dependencies]
actix-web.workspace = true
env_logger.workspace = true
log.workspace = true
5 changes: 3 additions & 2 deletions basics/hello-world/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,9 @@ async fn index(req: HttpRequest) -> &'static str {

#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

log::info!("starting HTTP server at http://localhost:8080");

HttpServer::new(|| {
App::new()
Expand Down
1 change: 1 addition & 0 deletions basics/state/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ edition = "2021"
[dependencies]
actix-web.workspace = true
env_logger.workspace = true
log.workspace = true
5 changes: 3 additions & 2 deletions basics/state/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,15 @@ async fn index(

#[actix_web::main]
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

// Create some global state prior to building the server
#[allow(clippy::mutex_atomic)] // it's intentional.
let counter_mutex = Data::new(Mutex::new(0usize));
let counter_atomic = Data::new(AtomicUsize::new(0usize));

log::info!("starting HTTP server at http://localhost:8080");

// move is necessary to give closure below ownership of counter1
HttpServer::new(move || {
// Create some thread-local state
Expand Down
3 changes: 2 additions & 1 deletion https-tls/openssl/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
[package]
name = "openssl-example"
name = "tls-openssl"
version = "1.0.0"
edition = "2021"

[dependencies]
actix-web = { workspace = true, features = ["openssl"] }
env_logger.workspace = true
log.workspace = true
openssl = "0.10"
7 changes: 3 additions & 4 deletions https-tls/openssl/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,7 @@ async fn index(req: HttpRequest) -> Result<HttpResponse, Error> {

#[actix_web::main]
async fn main() -> io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=debug");
env_logger::init();

println!("Started http server: https://127.0.0.1:8443");
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

// load TLS keys
let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
Expand All @@ -25,6 +22,8 @@ async fn main() -> io::Result<()> {
.unwrap();
builder.set_certificate_chain_file("cert.pem").unwrap();

log::info!("starting HTTPS server at http://localhost:8443");

HttpServer::new(|| {
App::new()
// enable logger
Expand Down
5 changes: 3 additions & 2 deletions json/jsonrpc/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,11 +139,12 @@ impl AppState {

#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "info");
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

let network = Arc::new(RwLock::new(ObjNetwork::new()));

log::info!("starting HTTP server at http://localhost:8080");

HttpServer::new(move || {
let app_state = AppState::new(network.clone());
App::new()
Expand Down
2 changes: 1 addition & 1 deletion middleware/middleware-encrypted-payloads/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ actix-web.workspace = true
actix-web-lab.workspace = true

aes-gcm-siv = "0.11"
base64 = "0.20"
base64 = "0.21"
env_logger.workspace = true
futures-util.workspace = true
log.workspace = true
Expand Down
8 changes: 5 additions & 3 deletions middleware/middleware-encrypted-payloads/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@ All this to say, it provides a (fairly brittle) way to have handlers not need to

## Usage

Using [HTTPie] throughout for simplicity.

```console
$ http POST :8080/encrypt id:=1234 data=abcde > tmp.json
POST /reverse HTTP/1.1
Content-Length: 76
HTTP/1.1 200 OK
Content-Type: application/json

{
Expand All @@ -28,7 +29,6 @@ Content-Type: application/json

$ cat tmp.json | http -v POST :8080/reverse
HTTP/1.1 200 OK
Content-Length: 66
Content-Type: application/json

{
Expand All @@ -49,3 +49,5 @@ The server logs would look something like
[INFO middleware_encrypted_payloads] encrypting response 1234
[INFO actix_web::middleware::logger] 127.0.0.1 "POST /reverse HTTP/1.1" 200 66 "-" "-" 0.000425
```

[httpie]: https://httpie.io/cli
13 changes: 7 additions & 6 deletions middleware/middleware-encrypted-payloads/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use actix_web::{
};
use actix_web_lab::middleware::{from_fn, Next};
use aes_gcm_siv::{aead::Aead as _, Aes256GcmSiv, KeyInit as _, Nonce};
use base64::prelude::*;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
Expand Down Expand Up @@ -34,10 +35,10 @@ async fn make_encrypted(

// this nonce should actually be unique per message in a production environment
let nonce = Nonce::from_slice(b"unique nonce");
let nonce_b64 = Some(base64::encode(nonce));
let nonce_b64 = Some(BASE64_STANDARD.encode(nonce));

let data_enc = cipher.encrypt(nonce, data.as_bytes()).unwrap();
let data_enc = base64::encode(data_enc);
let data_enc = BASE64_STANDARD.encode(data_enc);

web::Json(Req {
id,
Expand Down Expand Up @@ -98,11 +99,11 @@ async fn encrypt_payloads(
log::info!("decrypting request {id:?}");

// decode nonce from payload
let nonce = base64::decode(nonce.unwrap()).unwrap();
let nonce = BASE64_STANDARD.decode(nonce.unwrap()).unwrap();
let nonce = Nonce::from_slice(&nonce);

// decode and decrypt data field
let data_enc = base64::decode(&data).unwrap();
let data_enc = BASE64_STANDARD.decode(&data).unwrap();
let data = cipher.decrypt(nonce, data_enc.as_slice()).unwrap();

// construct request body format with plaintext data
Expand Down Expand Up @@ -136,11 +137,11 @@ async fn encrypt_payloads(

// generate and encode nonce for later
let nonce = Nonce::from_slice(b"unique nonce");
let nonce_b64 = Some(base64::encode(nonce));
let nonce_b64 = Some(BASE64_STANDARD.encode(nonce));

// encrypt and encode data field
let data_enc = cipher.encrypt(nonce, data.as_bytes()).unwrap();
let data_enc = base64::encode(data_enc);
let data_enc = BASE64_STANDARD.encode(data_enc);

// re-pack response into JSON format
let res_body = Res {
Expand Down
9 changes: 5 additions & 4 deletions middleware/middleware-ext-mut/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::{env, io};
use std::io;

use actix_web::{
middleware,
Expand All @@ -7,7 +7,7 @@ use actix_web::{
};

mod add_msg;
use crate::add_msg::{AddMsg, Msg};
use self::add_msg::{AddMsg, Msg};

// wrap route in our middleware factory
async fn index(msg: Option<ReqData<Msg>>) -> HttpResponse {
Expand All @@ -21,8 +21,9 @@ async fn index(msg: Option<ReqData<Msg>>) -> HttpResponse {

#[actix_web::main]
async fn main() -> io::Result<()> {
env::set_var("RUST_LOG", "info");
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

log::info!("starting HTTP server at http://localhost:8080");

HttpServer::new(|| {
App::new()
Expand Down
8 changes: 5 additions & 3 deletions templating/askama/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@ version = "1.0.0"
edition = "2021"

[dependencies]
env_logger.workspace = true
actix-web-lab.workspace = true
actix-web.workspace = true
askama = "0.11.0"
askama = "0.12"
env_logger.workspace = true
log.workspace = true

[build-dependencies]
askama = "0.11.0"
askama = "0.12"
20 changes: 11 additions & 9 deletions templating/askama/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::HashMap;

use actix_web::{middleware, web, App, HttpResponse, HttpServer, Result};
use actix_web::{middleware, web, App, HttpServer, Responder, Result};
use actix_web_lab::respond::Html;
use askama::Template;

#[derive(Template)]
Expand All @@ -14,26 +15,27 @@ struct UserTemplate<'a> {
#[template(path = "index.html")]
struct Index;

async fn index(query: web::Query<HashMap<String, String>>) -> Result<HttpResponse> {
let s = if let Some(name) = query.get("name") {
async fn index(query: web::Query<HashMap<String, String>>) -> Result<impl Responder> {
let html = if let Some(name) = query.get("name") {
UserTemplate {
name,
text: "Welcome!",
}
.render()
.unwrap()
.expect("template should be valid")
} else {
Index.render().unwrap()
Index.render().expect("template should be valid")
};
Ok(HttpResponse::Ok().content_type("text/html").body(s))

Ok(Html(html))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info");
env_logger::init();
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));

log::info!("starting HTTP server at http://localhost:8080");

// start http server
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
Expand Down
4 changes: 2 additions & 2 deletions templating/minijinja/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@ actix-utils.workspace = true

env_logger.workspace = true
log.workspace = true
minijinja = { version = "0.28", features = ["source"] }
minijinja-autoreload = "0.28"
minijinja = { version = "0.30", features = ["source"] }
minijinja-autoreload = "0.30"
2 changes: 1 addition & 1 deletion templating/sailfish/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ actix-web-lab.workspace = true

env_logger.workspace = true
log.workspace = true
sailfish = "0.5"
sailfish = "0.6"
3 changes: 2 additions & 1 deletion templating/tera/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ actix-web.workspace = true
actix-web-lab.workspace = true

env_logger.workspace = true
tera = "1.8.0"
log.workspace = true
tera = "1.8"
Loading

0 comments on commit 6424e4e

Please sign in to comment.