Skip to content

Commit

Permalink
Completely revamp, redo examples.
Browse files Browse the repository at this point in the history
The new examples directory...

  * Contains a `README.md` explaining each example.
  * Consolidates examples into more complete chunks.
  * Is just better.

Resolves rwf2#1447.
  • Loading branch information
SergioBenitez committed Apr 8, 2021
1 parent cfd5af3 commit 50c9e88
Show file tree
Hide file tree
Showing 141 changed files with 2,026 additions and 1,832 deletions.
36 changes: 36 additions & 0 deletions core/lib/tests/scoped-uri.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use rocket::{get, routes};
use rocket::local::blocking::Client;

mod inner {
use rocket::uri;

#[rocket::get("/")]
pub fn hello() -> String {
format!("Hello! Try {}.", uri!(super::hello_name: "Rust 2018"))
}
}

#[get("/<name>")]
fn hello_name(name: String) -> String {
format!("Hello, {}! This is {}.", name, rocket::uri!(hello_name: &name))
}

fn rocket() -> rocket::Rocket {
rocket::ignite()
.mount("/", routes![hello_name])
.mount("/", rocket::routes![inner::hello])
}

#[test]
fn test_inner_hello() {
let client = Client::debug(rocket()).unwrap();
let response = client.get("/").dispatch();
assert_eq!(response.into_string(), Some("Hello! Try /Rust%202018.".into()));
}

#[test]
fn test_hello_name() {
let client = Client::debug(rocket()).unwrap();
let response = client.get("/Rust%202018").dispatch();
assert_eq!(response.into_string().unwrap(), "Hello, Rust 2018! This is /Rust%202018.");
}
43 changes: 15 additions & 28 deletions examples/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,35 +1,22 @@
[workspace]
members = [
"config",
"cookies",
"errors",
"databases",
"error-handling",
"fairings",
"forms",
"hello_person",
"query_params",
"hello_world",
"manual_routes",
"optional_redirect",
"redirect",
"static_files",
"todo",
"content_types",
"ranking",
"testing",
"request_local_state",
"request_guard",
"stream",
"json",
"msgpack",
"handlebars_templates",
"tera_templates",
"config",
"raw_upload",
"pastebin",
"hello",
"manual-routing",
"responders",
"serialization",
"state",
"managed_queue",
"uuid",
"session",
"raw_sqlite",
"static-files",
"templating",
"testing",
"tls",
"fairings",
"hello_2018",
"uuid",

"pastebin",
"todo",
]
85 changes: 85 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# Rocket Examples

This directory contains projects showcasing Rocket's features.

## Applications

* **[`pastebin`](./pastebin)**

A simple, API-only pastebin application, similar to https://paste.rs. Stores
pastes locally on the file system. Implements a custom parameter guard,
`PasteId`, to parse and validate paste identifiers.

* **[`todo`](./todo)**

A todo app with a web UI to add, delete, and mark/unmark items. Uses a
SQLite database driven by diesel. Runs migrations automatically at start-up.
Uses tera to render templates.

## Feature Examples

* **[`config`](./config)** - Illustrates how to extract values from a Rocket
`Figment`, how to store and retrieve an application specific configuration
in managed state using `AdHoc::config()`, and how to set configuration
values in `Rocket.toml`.

* **[`cookies`](./cookies)** - Uses cookies to create a client-side message
box. Uses private cookies for a session-based authentication.

* **[`databases`](./databases)** - Implements a CRUD-like "blog" JSON API
backed by a SQLite database driven by each of `sqlx`, `diesel`, and
`rusqlite`. Runs migrations automatically for the former two drivers. Uses
`contrib` database support for the latter two drivers.

* **[`error-handling`](./error-handling)** - Exhibits the use of scoped
catchers; contains commented out lines that will cause a launch-time error
with code to custom-display the error.

* **[`fairings`](./fairings)** - Exemplifies creating a custom `Counter`
fairing and using `AdHoc` fairings.

* **[`forms`](./forms)** - Showcases all of Rocket's form support features
including multipart file uploads, ad-hoc validations, field renaming, and
use of form context for staged forms.

* **[`hello`](./hello)** - Basic example of Rocket's core features: route
declaration with path and query parameters, both simple and compound,
mounting, launching, testing, and returning simple responses. Also showcases
using UTF-8 in route declarations and responses.

* **[`manual-routing`](./manual-routing)** - An example eschewing Rocket's
codegen in favor of manual routing. This should be seen as last-ditch
effort, much like `unsafe` in Rust, as manual routing _also_ eschews many of
Rocket's automatic web security guarantees.

* **[`responders`](./responders)** - Illustrates the use of many of Rocket's
built-in responders: `Stream`, `Redirect`, `File`, `NamedFile`, `content`
for manually setting Content-Types, and `Either`. In the process, showcases
using `TempFile` for raw uploads. Also illustrates the creation of a custom,
derived `Responder`.

* **[`serialization`](./serialization)** - Showcases JSON and MessagePack
(de)serialization support in `contrib` by implementing a CRUD-like message
API in JSON and a simply read/echo API in MessagePack.

* **[`state`](./state)** - Illustrates the use of request-local state and
managed state. Uses request-local state to cache "expensive" per-request
operations. Uses managed state to implement a simple index hit counter. Also
uses managed state to store, retrieve, and push/pop from a concurrent queue.

* **[`static-files`](./static-files)** - Uses `contrib` `StaticFiles` serve
static files. Also creates a `second` manual yet safe version.

* **[`templating`](./templating)** - Illustrates using `contrib` `templates`
support with identical examples for handlebars and tera.

* **[`testing`](./testing)** - Uses Rocket's `local` libraries to test an
application. Showcases necessary use of the `async` `Client`. Note that all
examples contains tests, themselves serving as examples for how to test
Rocket applications.

* **[`tls`](./tls)** - Illustrates configuring TLS with a variety of key pair
kinds.

* **[`uuid`](./uuid)** - Uses UUID support in `contrib`, converting between
`contrib::Uuid` type and the `uuid` crate `Uuid`.
1 change: 1 addition & 0 deletions examples/config/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ publish = false

[dependencies]
rocket = { path = "../../core/lib", features = ["secrets"] }
serde = { version = "1", features = ["derive"] }
10 changes: 7 additions & 3 deletions examples/config/Rocket.toml
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
# Except for the secret key, none of these are actually needed; Rocket has sane
# defaults. We show all of them here explicitly for demonstrative purposes.

[global.limits]
[default.limits]
forms = "64 kB"
json = "1 MiB"
msgpack = "2 MiB"
"file/jpg" = "5 MiB"

[default]
key = "a default app-key"
extra = false

[debug]
address = "127.0.0.1"
port = 8000
workers = 1
keep_alive = 0
log_level = "normal"
hi = "Hello!" # this is an unused extra; maybe application specific?
is_extra = true # this is an unused extra; maybe application specific?

[release]
address = "127.0.0.1"
Expand All @@ -24,3 +26,5 @@ keep_alive = 5
log_level = "critical"
# don't use this key! generate your own and keep it private!
secret_key = "hPRYyVRiMyxpw5sBB1XeCMN1kFsDCqKvBi2QJxBVHQk="
key = "a release app-key"
extra = false
31 changes: 23 additions & 8 deletions examples/config/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
#[macro_use] extern crate rocket;

#[cfg(test)] mod tests;

use rocket::{State, Config};
use rocket::fairing::AdHoc;

// This example's illustration is the Rocket.toml file. Running this server will
// print the config, however.
#[rocket::launch]
fn rocket() -> rocket::Rocket {
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct AppConfig {
key: String,
port: u16
}

#[get("/")]
fn read_config(rocket_config: &Config, app_config: State<'_, AppConfig>) -> String {
format!("{:#?}\n{:#?}", app_config, rocket_config)
}

// See Rocket.toml file. Running this server will print the config. Try running
// with `ROCKET_PROFILE=release` manually by setting the environment variable
// and automatically by compiling with `--release`.
#[launch]
fn rocket() -> _ {
rocket::ignite()
.attach(AdHoc::on_liftoff("Config Reader", |rocket| Box::pin(async move {
let value = rocket.figment().find_value("").unwrap();
println!("{:#?}", value);
})))
.mount("/", routes![read_config])
.attach(AdHoc::config::<AppConfig>())
}
11 changes: 0 additions & 11 deletions examples/content_types/Cargo.toml

This file was deleted.

67 changes: 0 additions & 67 deletions examples/content_types/src/main.rs

This file was deleted.

41 changes: 0 additions & 41 deletions examples/content_types/src/tests.rs

This file was deleted.

2 changes: 1 addition & 1 deletion examples/cookies/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ edition = "2018"
publish = false

[dependencies]
rocket = { path = "../../core/lib" }
rocket = { path = "../../core/lib", features = ["secrets"] }

[dependencies.rocket_contrib]
path = "../../contrib/lib"
Expand Down
File renamed without changes.
Loading

0 comments on commit 50c9e88

Please sign in to comment.