### Full Rocket Testing Example Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Combines setup, request dispatching, and response assertion into a complete test case for a 'Hello, world!' endpoint. This demonstrates a typical testing workflow. ```rust # #[macro_use] extern crate rocket; # use rocket::{Rocket, Build}; #[get("/")] fn hello() -> &'static str { "Hello, world!" } # /* #[launch] # */ fn rocket() -> Rocket { rocket::build().mount("/", routes![hello]) } # /* #[cfg(test)] # */ mod test { use super::rocket; use rocket::local::blocking::Client; use rocket::http::Status; # /* #[test] # */ pub fn hello_world() { # /* let client = Client::tracked(rocket()).expect("valid rocket instance"); # */ # let client = Client::debug(rocket()).expect("valid rocket instance"); let mut response = client.get(uri!(super::hello)).dispatch(); assert_eq!(response.status(), Status::Ok); assert_eq!(response.into_string().unwrap(), "Hello, world!"); } } # fn main() { test::hello_world(); } ``` -------------------------------- ### Run Rocket 'hello' Example Source: https://github.com/rwf2/rocket/blob/master/docs/guide/02-quickstart.md Clone the Rocket repository and run the 'hello' example using Cargo. Ensure to adjust Cargo.toml when copying examples for your own use. ```sh git clone https://github.com/rwf2/Rocket cd Rocket git checkout master cd examples/hello cargo run ``` -------------------------------- ### Run a Rocket Example Project Source: https://github.com/rwf2/rocket/blob/master/README.md Commands to navigate to an example directory and execute the project using Cargo. ```sh cd examples/hello cargo run ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/rwf2/rocket/blob/master/docs/guide/10-configuration.md Example of Rocket.toml configuration for secret key, limits, and TLS settings. ```toml secret_key = "hPrYyЭRiMyµ5sBB1π+CMæ1køFsåqKvBiQJxBVHQk=" [default.limits] form = "64 kB" json = "1 MiB" msgpack = "2 MiB" "file/jpg" = "5 MiB" [default.tls] certs = "path/to/cert-chain.pem" key = "path/to/key.pem" [default.shutdown] ctrlc = true signals = ["term", "hup"] grace = 5 mercy = 5 ``` -------------------------------- ### Example Rocket.toml Configuration Source: https://github.com/rwf2/rocket/blob/master/docs/guide/10-configuration.md A sample Rocket.toml file demonstrating profile-specific settings and default overrides. ```toml ## defaults for _all_ profiles [default] address = "0.0.0.0" limits = { form = "64 kB", json = "1 MiB" } ## set only when compiled in debug mode, i.e, `cargo build` [debug] port = 8000 ## only the `json` key from `default` will be overridden; `form` will remain limits = { json = "10MiB" } ## set only when the `nyc` profile is selected [nyc] port = 9001 ## set only when compiled in release mode, i.e, `cargo build --release` [release] port = 9999 ip_header = false proxy_proto_header = "X-Forwarded-Proto" # NOTE: Don't (!) use this key! Generate your own and keep it private! # e.g. via `head -c64 /dev/urandom | base64` secret_key = "hPrYyЭRiMyµ5sBB1π+CMæ1køFsåqKvBiQJxBVHQk=" ``` ```toml [default] address = "127.0.0.1" port = 8000 workers = 16 max_blocking = 512 keep_alive = 5 ident = "Rocket" ip_header = "X-Real-IP" # set to `false` to disable proxy_proto_header = false # set to `false` (the default) to disable log_level = "normal" temp_dir = "/tmp" cli_colors = true # NOTE: Don't (!) use this key! Generate your own and keep it private! ``` -------------------------------- ### Environment Variable Configuration Examples Source: https://github.com/rwf2/rocket/blob/master/docs/guide/10-configuration.md Examples demonstrating how to set Rocket configuration values using environment variables. Note that environment variables take precedence over TOML settings. ```sh ROCKET_FLOAT=3.14 ``` ```sh ROCKET_ARRAY=[1,"b",3.14] ``` ```sh ROCKET_STRING=Hello ``` ```sh ROCKET_STRING="Hello There" ``` ```sh ROCKET_KEEP_ALIVE=1 ``` ```sh ROCKET_IDENT=Rocket ``` ```sh ROCKET_IDENT="Hello Rocket" ``` ```sh ROCKET_IDENT=false ``` ```sh ROCKET_TLS={certs="abc",key="foo/bar"} ``` ```sh ROCKET_LIMITS={form="64 KiB"} ``` -------------------------------- ### Define a Rocket Route and Launch Source: https://github.com/rwf2/rocket/blob/master/README.md Uses the #[get] macro to define a route with dynamic parameters and the #[launch] macro to start the application. ```rust #[macro_use] extern crate rocket; #[get("//")] fn hello(name: &str, age: u8) -> String { format!("Hello, {} year old named {}!", age, name) } #[launch] fn rocket() -> _ { rocket::build().mount("/hello", routes![hello]) } ``` -------------------------------- ### Install cargo-fuzz Source: https://github.com/rwf2/rocket/blob/master/core/lib/fuzz/README.md Installs the cargo-fuzz tool globally using the cargo package manager. ```sh cargo install -f cargo-fuzz ``` -------------------------------- ### Execute test.sh script Source: https://github.com/rwf2/rocket/blob/master/CONTRIBUTING.md Usage information and examples for the test.sh script used to run project test suites. ```sh USAGE: ./scripts/test.sh [+] [--help|-h] [--] OPTIONS: + Forwarded to Cargo to select toolchain. --help, -h Print this help message and exit. -- Run the specified test suite. (Run without -- to run default tests.) AVAILABLE OPTIONS: default all core contrib examples benchmarks testbench ui EXAMPLES: ./scripts/test.sh # Run default tests on current toolchain. ./scripts/test.sh +stable --all # Run all tests on stable toolchain. ./scripts/test.sh --ui # Run UI tests on current toolchain. ``` -------------------------------- ### Prepare SQLx Migrations for Offline Checking Source: https://github.com/rwf2/rocket/blob/master/examples/databases/README.md Install the SQLx CLI with SQLite features and then use it to prepare query metadata for offline checking. The DATABASE_URL should point to your SQLite database file. ```shell cargo install sqlx-cli --no-default-features --features sqlite DATABASE_URL="sqlite:$(pwd)/db/sqlx/db.sqlite" cargo sqlx prepare ``` -------------------------------- ### Example Rocket Generated Code Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md This is an example of the debug output for a Rocket route handler. It shows the generated Rust code for the 'world' route, including the facade request handler. ```rust note: emitting Rocket code generation debug output --> examples/hello/src/main.rs:14:1 | 14 | #[get("/world")] | ^^^^^^^^^^^^^^^^ | = note: impl world { fn into_info(self) -> rocket::StaticRouteInfo { fn monomorphized_function<'_b>( __req: &'_b rocket::request::Request<'_>, __data: rocket::data::Data, ) -> ::rocket::route::BoxFuture<'_b> { ::std::boxed::Box::pin(async move { let ___responder = world(); ::rocket::handler::Outcome::from(__req, ___responder) }) } ::rocket::StaticRouteInfo { name: "world", method: ::rocket::http::Method::Get, path: "/world", handler: monomorphized_function, format: ::std::option::Option::None, rank: ::std::option::Option::None, sentinels: sentinels![&'static str], } } } ``` -------------------------------- ### Return a static string responder Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md A basic example of a handler returning a static string as a response. ```rust #[get("/string")] fn handler() -> &'static str { "Hello there! I'm a string!" } ``` -------------------------------- ### Run Diesel SQLite Migrations Source: https://github.com/rwf2/rocket/blob/master/examples/databases/README.md Install the Diesel CLI with SQLite features and then use it to apply or redo migrations for a SQLite database. Ensure the DATABASE_URL is correctly set. ```shell cargo install diesel_cli --no-default-features --features sqlite DATABASE_URL="db/diesel/db.sqlite" diesel migration --migration-dir db/diesel/migrations redo ``` -------------------------------- ### Example of `FromUriParam` Conversion for `String` Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md Illustrates a `FromUriParam` implementation that allows an `&str` to be used in a `uri!` invocation for route URI parameters declared as `String`. This shows how types can be converted before URI display. ```rust # use rocket::http::uri::fmt::{FromUriParam, Part}; # struct S; # type String = S; impl<'a, P: Part> FromUriParam for String { type Target = &'a str; # fn from_uri_param(s: &'a str) -> Self::Target { "hi" } } ``` -------------------------------- ### Basic Rocket Application Structure Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Defines a simple Rocket application with a single GET route. Separating application creation from launching facilitates testing. ```rust # #[macro_use] extern crate rocket; #[get("/")] fn hello() -> &'static str { "Hello, world!" } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![hello]) } ``` -------------------------------- ### Full TLS Configuration with Ciphers in Rocket.toml Source: https://github.com/rwf2/rocket/blob/master/docs/guide/10-configuration.md An example of a complete TLS configuration in Rocket.toml, including custom cipher suites and server cipher preference. ```toml [default.tls] certs = "/ssl/cert.pem" key = "/ssl/key.pem" prefer_server_cipher_order = false ciphers = [ "TLS_CHACHA20_POLY1305_SHA256", "TLS_AES_256_GCM_SHA384", "TLS_AES_128_GCM_SHA256", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", ] ``` -------------------------------- ### Launching Rocket with #[launch] Source: https://github.com/rwf2/rocket/blob/master/docs/guide/04-overview.md The preferred method for launching Rocket applications. It automatically generates a main function, sets up an async runtime, and starts the server. The return type can be inferred using `_`. ```rust #[macro_use] extern crate rocket; #[get("/world")] fn world() -> &'static str { "Hello, world!" } #[launch] fn rocket() -> _ { rocket::build().mount("/hello", routes![world]) } ``` -------------------------------- ### Mount Routes to a Base Path Source: https://github.com/rwf2/rocket/blob/master/docs/guide/04-overview.md Mount a list of routes under a specified base path using the `mount` method. This namespaces the routes, so `GET /hello/world` will be directed to the `world` function. ```rust # #[macro_use] extern crate rocket; # #[get("/world")] # fn world() -> &'static str { # "hello, world!" # } rocket::build().mount("/hello", routes![world]); ``` -------------------------------- ### Upload a text document with curl Source: https://github.com/rwf2/rocket/blob/master/docs/guide/12-pastebin.md Example of uploading a text document using curl to a pastebin service. This demonstrates the expected interaction with the finished product. ```sh curl --data-binary @test.txt https://paste.rs/ # => https://paste.rs/IYu ``` -------------------------------- ### Async Route Handler in Rocket Source: https://github.com/rwf2/rocket/blob/master/docs/guide/04-overview.md Example of an asynchronous route handler in Rocket. Async routes allow for non-blocking I/O operations using `async/await`. ```rust rocket::build() .mount("/hello", routes![world]) .launch(); ``` -------------------------------- ### Attach AdHoc Fairings for Liftoff, Request Rewriting, and Shutdown in Rust Source: https://github.com/rwf2/rocket/blob/master/docs/guide/08-fairings.md This example demonstrates attaching multiple AdHoc fairings to a Rocket instance. It includes a liftoff fairing to print a message on launch, a request fairing to rewrite methods to PUT, and a shutdown fairing to print a message on exit. Ensure Rocket and AdHoc are correctly imported. ```rust use rocket::fairing::AdHoc; use rocket::http::Method; rocket::build() .attach(AdHoc::on_liftoff("Liftoff Printer", |_| Box::pin(async move { println!("...annnddd we have liftoff!"); }))) .attach(AdHoc::on_request("Put Rewriter", |req, _| Box::pin(async move { req.set_method(Method::Put); }))) .attach(AdHoc::on_shutdown("Shutdown Printer", |_| Box::pin(async move { println!("...shutdown has commenced!"); }))); ``` -------------------------------- ### Implementing `FromRequest` with State Access Source: https://github.com/rwf2/rocket/blob/master/docs/guide/07-state.md Example of a `FromRequest` implementation that accesses application state using `Request::guard()` and `Rocket::state()`. Use this when your guard needs access to globally managed state. ```rust struct Item<'r>(&'r str); #[rocket::async_trait] impl<'r> FromRequest<'r> for Item<'r> { type Error = (); async fn from_request(request: &'r Request<'_>) -> request::Outcome { // Using `State` as a request guard. Use `inner()` to get an `'r`. let outcome = request.guard::<&State>().await .map(|my_config| Item(&my_config.user_val)); // Or alternatively, using `Rocket::state()`: let outcome = request.rocket().state::() .map(|my_config| Item(&my_config.user_val)) .or_forward(Status::InternalServerError); outcome } } ``` -------------------------------- ### Declare a Basic Route Source: https://github.com/rwf2/rocket/blob/master/docs/guide/04-overview.md Declare a route with a static path and a handler function. Use `#[get]`, `#[post]`, or `#[put]` for HTTP methods, or `#[catch]` for error pages. ```rust # #[macro_use] extern crate rocket; #[get("/world")] // <- route attribute fn world() -> &'static str { // <- request handler "hello, world!" } ``` -------------------------------- ### Default Ranking Example Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Demonstrates default ranking where `foo_bar` with a 'partial' path color has higher precedence than `everything` with a 'wild' path color, preventing a routing collision. ```rust # #[macro_use] extern crate rocket; #[get("/foo/<_>/bar")] fn foo_bar() { } #[get("/<_..>")] fn everything() { } # # // Ensure there are no collisions. # rocket_docs_tests::client(routes![foo_bar, everything]); ``` -------------------------------- ### Initialize WebSocket Client Source: https://github.com/rwf2/rocket/blob/master/examples/upgrade/static/index.html Sets up the WebSocket connection and event listeners. Ensure the WebSocket server is running at the specified URI. ```javascript var wsUri = "ws://127.0.0.1:8000/echo?raw"; var log; function init() { log = document.getElementById("log"); form = document.getElementsByTagName("form")[0]; message = document.getElementById("message"); testWebSocket(); form.addEventListener("submit", (e) => { e.preventDefault(); if (message.value !== "") { sendMessage(message.value); message.value = ""; } }); } function testWebSocket() { websocket = new WebSocket(wsUri); websocket.onopen = onOpen; websocket.onclose = onClose; websocket.onmessage = onMessage; websocket.onerror = onError; } function onOpen(evt) { writeLog("CONNECTED"); sendMessage("Hello, Rocket!"); } function onClose(evt) { writeLog("Websocket DISCONNECTED"); } function onMessage(evt) { writeLog('RESPONSE: ' + evt.data+''); } function onError(evt) { writeLog('ERROR: ' + evt.data); } function sendMessage(message) { writeLog("SENT: " + message); websocket.send(message); } function writeLog(message) { var pre = document.createElement("p"); pre.innerHTML = message; log.prepend(pre); } window.addEventListener("load", init, false); ``` -------------------------------- ### Create a Basic Rocket Application Source: https://context7.com/rwf2/rocket/llms.txt Uses the #[launch] attribute to initialize the server and defines routes with HTTP method attributes. ```rust #[macro_use] extern crate rocket; #[get("/")] fn index() -> &'static str { "Hello, world!" } #[get("/hello/")] fn hello(name: &str) -> String { format!("Hello, {}!", name) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![index]) .mount("/api", routes![hello]) } ``` -------------------------------- ### Define a basic GET route Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Specifies a route that matches only GET requests to the /world path. ```rust #[macro_use] extern crate rocket; # fn main() {} #[get("/world")] fn handler() { /* .. */ } ``` -------------------------------- ### Create Hello World Application Source: https://github.com/rwf2/rocket/blob/master/docs/guide/03-getting-started.md Defines the main entry point and index route for a Rocket application. ```rust #[macro_use] extern crate rocket; #[get("/")] fn index() -> &'static str { "Hello, world!" } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![index]) } ``` -------------------------------- ### Nested Form Submission Example Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Example of asserting that a nested form structure parses correctly from a URL-encoded string. ```rust # use rocket::form::FromForm; # use rocket_docs_tests::{assert_form_parses, assert_not_form_parses}; # #[derive(FromForm, Debug, PartialEq)] struct MyForm { owner: Person, pet: Pet, } # #[derive(FromForm, Debug, PartialEq)] struct Person { name: String } # #[derive(FromForm, Debug, PartialEq)] struct Pet { name: String, good_pet: bool, } # assert_form_parses! { MyForm, "owner.name=Bob&pet.name=Sally&pet.good_pet=on", # "owner.name=Bob&pet.name=Sally&pet.good_pet=yes", # "owner.name=Bob&pet.name=Sally&pet.good_pet=on", ``` -------------------------------- ### Initialize Cargo Project Source: https://github.com/rwf2/rocket/blob/master/docs/guide/03-getting-started.md Creates a new binary-based Cargo project and navigates into the directory. ```sh cargo new hello-rocket --bin cd hello-rocket ``` -------------------------------- ### Dispatching a GET Request in Rocket Tests Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Dispatches a GET request to a specified URI and captures the application's response. This is a common step in testing API endpoints. ```rust # use rocket::uri; # #[rocket::launch] # fn rocket() -> _ { # rocket::build().reconfigure(rocket::Config::debug_default()) # } # #[rocket::get("/")] # fn hello() -> &'static str { "Hello, world!" } # use rocket::local::blocking::Client; # let client = Client::tracked(rocket()).expect("valid rocket instance"); let mut response = client.get(uri!(hello)).dispatch(); ``` -------------------------------- ### Serve Static Files with Rocket Source: https://context7.com/rwf2/rocket/llms.txt Demonstrates manual file serving with custom logic using NamedFile and automatic serving using FileServer. ```rust #[macro_use] extern crate rocket; use std::path::{Path, PathBuf}; use rocket::fs::{FileServer, NamedFile, relative}; // Manual file serving with custom logic #[get("/download/")] async fn download(file: PathBuf) -> Option { let path = Path::new(relative!("files")).join(file); // Only serve files, not directories if path.is_file() { NamedFile::open(path).await.ok() } else { None } } // Serve index.html for directories #[get("/pages/")] async fn pages(path: PathBuf) -> Option { let mut path = Path::new(relative!("pages")).join(path); if path.is_dir() { path.push("index.html"); } NamedFile::open(path).await.ok() } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![download, pages]) // Automatic static file serving .mount("/static", FileServer::new(relative!("static"))) .mount("/assets", FileServer::new("/www/assets")) } ``` -------------------------------- ### Handle Dynamic Path Parameters Source: https://context7.com/rwf2/rocket/llms.txt Demonstrates capturing path segments, serving files with PathBuf, and using route ranking for type-based forwarding. ```rust #[macro_use] extern crate rocket; use std::path::PathBuf; use rocket::fs::NamedFile; // Single dynamic parameter with type validation #[get("/user///")] fn user(id: usize, name: &str, active: bool) -> String { if active { format!("Active user #{}: {}", id, name) } else { format!("Inactive user #{}: {}", id, name) } } // Multiple segments capture for file serving #[get("/files/")] async fn files(path: PathBuf) -> Option { NamedFile::open(std::path::Path::new("static/").join(path)).await.ok() } // Ranked routes for type-based forwarding #[get("/item/")] fn item_by_id(id: usize) -> String { format!("Item by ID: {}", id) } #[get("/item/", rank = 2)] fn item_by_slug(id: &str) -> String { format!("Item by slug: {}", id) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![user, files, item_by_id, item_by_slug]) } ``` -------------------------------- ### Get All Post IDs via HTTPie Source: https://github.com/rwf2/rocket/blob/master/examples/databases/README.md Use httpie to send a GET request to retrieve a JSON array of all blog post IDs. This is useful for listing available posts. ```shell http http://127.0.0.1:8000/sqlx > [ 2128, 2129, 2130, 2131 ] ``` -------------------------------- ### Use Option as a responder Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md Returns a 200 OK if the file exists, otherwise returns a 404 Not Found. ```rust # use std::path::{Path, PathBuf}; use rocket::fs::NamedFile; #[get("/")] async fn files(file: PathBuf) -> Option { NamedFile::open(Path::new("static/").join(file)).await.ok() } ``` -------------------------------- ### Declare JSON Accept Header for GET Route Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md For non-payload-supporting methods like `GET`, the `format` parameter checks the `Accept` header. Only requests where `application/json` is the preferred media type will match. ```rust #[get("/user/", format = "json")] fn user(id: usize) -> User { /* .. */ } ``` -------------------------------- ### Create a skeleton Rocket application Source: https://github.com/rwf2/rocket/blob/master/docs/guide/12-pastebin.md Sets up the basic structure for a Rocket application in src/main.rs. This includes the necessary extern crate and launch macro. ```rust #[macro_use] extern crate rocket; #[launch] fn rocket() -> _ { rocket::build() } ``` -------------------------------- ### Get Specific Post via HTTPie Source: https://github.com/rwf2/rocket/blob/master/examples/databases/README.md Use httpie to send a GET request to retrieve a specific blog post by its ID. The API returns the post's JSON object. ```shell http http://127.0.0.1:8000/sqlx/2128 > { "id": 2128, "text": "Hello, world.", "title": "Title" } ``` -------------------------------- ### Implementing Responder for String Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md Example implementation of the Responder trait for the String type. ```rust # #[macro_use] extern crate rocket; # fn main() {} use std::io::Cursor; use rocket::request::Request; use rocket::response::{self, Response, Responder}; use rocket::http::ContentType; # struct String(std::string::String); #[rocket::async_trait] impl<'r> Responder<'r, 'static> for String { fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> { Response::build() .header(ContentType::Plain) # /* .sized_body(self.len(), Cursor::new(self)) # */ # .sized_body(self.0.len(), Cursor::new(self.0)) .ok() } } ``` -------------------------------- ### Creating a Test Client for Rocket Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Initializes a tracked client for a Rocket instance to facilitate testing. Use `expect` and `unwrap` during testing as tests should panic on failure. ```rust # #[rocket::launch] # fn rocket() -> _ { # rocket::build().reconfigure(rocket::Config::debug_default()) # } # use rocket::local::blocking::Client; let client = Client::tracked(rocket()).expect("valid rocket instance"); ``` -------------------------------- ### Serve static files with FileServer Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Mounts a directory to a specific path to serve static files automatically. ```rust # #[macro_use] extern crate rocket; use rocket::fs::FileServer; #[launch] fn rocket() -> _ { rocket::build() // serve files from `/www/static` at path `/public` .mount("/public", FileServer::new("/www/static")) } ``` -------------------------------- ### Mounting Routes in Rocket Source: https://github.com/rwf2/rocket/blob/master/docs/guide/04-overview.md Demonstrates how to mount a route to multiple paths. This allows a single route handler to respond to requests on different base paths. ```rust rocket::build() .mount("/hello", routes![world]) .mount("/hi", routes![world]); ``` -------------------------------- ### Dynamic path route boilerplate Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Initial setup for a route utilizing dynamic path parameters. ```rust #[macro_use] extern crate rocket; # fn main() {} ``` -------------------------------- ### Parse Nested Struct HashMap Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Example of parsing form data into a HashMap where the value is a complex struct. ```rust # use std::collections::HashMap; # # use rocket::form::FromForm; # use rocket_docs_tests::{map, assert_form_parses}; # # #[derive(FromForm, Debug, PartialEq)] struct MyForm { ids: HashMap, } # #[derive(FromForm, Debug, PartialEq)] struct Person { name: String, age: usize } // These form strings... # assert_form_parses! { MyForm, "ids[0]name=Bob&ids[0]age=3&ids[1]name=Sally&ids[1]age=10", "ids[0]name=Bob&ids[1]age=10&ids[1]name=Sally&ids[0]age=3", "ids[0]name=Bob&ids[1]name=Sally&ids[0]age=3&ids[1]age=10", # => // ...which parse as this struct: MyForm { ids: map! { 0usize => Person { name: "Bob".into(), age: 3 }, 1usize => Person { name: "Sally".into(), age: 10 }, } } # }; ``` -------------------------------- ### Build Rocket Instance for Testing Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Construct a Rocket instance to represent your application for testing purposes. This is the first step in setting up local dispatching. ```rust let rocket = rocket::build(); # let _ = rocket; ``` -------------------------------- ### Dispatch Local Request Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Dispatch the constructed local request to get a response. This simulates a request to your Rocket application. ```rust # use rocket::local::blocking::Client; # let rocket = rocket::build(); # let client = Client::tracked(rocket).unwrap(); # let req = client.get("/"); let response = req.dispatch(); # let _ = response; ``` -------------------------------- ### Demonstrate route forwarding Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Shows a route signature that triggers request forwarding when parameter types do not match. ```rust # #[macro_use] extern crate rocket; # fn main() {} #[get("/hello///")] fn hello(name: &str, age: u8, cool: bool) { /* ... */ } ``` -------------------------------- ### Compile-time URI Type Mismatch Error Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md Example of a compile-time error when the type of a parameter provided to uri! does not match the route definition. ```rust --> examples/uri/src/main.rs:7:31 | 7 | let x = uri!(person(id = "10", name = "Mike Smith", age = Some(10))); | ^^^^ `FromUriParam` is not implemented for `usize` ``` -------------------------------- ### Compile-time URI Parameter Mismatch Error Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md Example of a compile-time error when the number of parameters provided to uri! does not match the route definition. ```rust error: `person` route uri expects 3 parameters but 1 was supplied --> examples/uri/main.rs:7:26 | 7 | let x = uri!(person("Mike Smith")); | ^^^^^^^^^^^^ | = note: expected parameters: id: Option , name: &str, age: Option ``` -------------------------------- ### Register a Catcher with Rocket Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Catchers must be registered with Rocket using the `register()` method and the `catchers!` macro. This example registers a 404 catcher. ```rust # #[macro_use] extern crate rocket; # use rocket::Request; # #[catch(404)] fn not_found(req: &Request) { /* .. */ } fn main() { rocket::build().register("/", catchers![not_found]); } ``` -------------------------------- ### Create a new Rocket project Source: https://github.com/rwf2/rocket/blob/master/docs/guide/12-pastebin.md Initializes a new Rust Cargo binary project for the Rocket pastebin application. This sets up the project structure. ```sh cargo new --bin rocket-pastebin cd rocket-pastebin ``` -------------------------------- ### Catcher with String Response Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md A catcher must return a type that implements `Responder`. This example shows a 404 catcher that returns a formatted string. ```rust # #[macro_use] extern crate rocket; # fn main() {} # use rocket::Request; #[catch(404)] fn not_found(req: &Request) -> String { format!("Sorry, '{}' is not a valid path.", req.uri()) } ``` -------------------------------- ### Building Rocket API Documentation Source: https://github.com/rwf2/rocket/blob/master/CONTRIBUTING.md Command to build the API documentation for the Rocket project. The -d flag can be used to prevent cleaning existing docs. ```bash mk-docs.sh mk-docs.sh -d ``` -------------------------------- ### Mounting Static Files and Templates Source: https://github.com/rwf2/rocket/blob/master/docs/guide/11-deploying.md Configures a Rocket application to serve static files from a directory and attach template support. Ensure the static and templates directories exist in the application's working directory at runtime. ```rust # #[macro_use] extern crate rocket; use rocket::fs::FileServer; use rocket_dyn_templates::Template; #[launch] fn rocket() -> _ { rocket::build() .mount("/", FileServer::new("./static")) .attach(Template::fairing()) } ``` -------------------------------- ### Incorrect Dependency Configuration Source: https://github.com/rwf2/rocket/blob/master/docs/guide/14-faq.md Example of an invalid Cargo.toml configuration mixing a crates.io version with a git dependency, which causes type mismatch errors. ```toml rocket = "0.6.0-dev" rocket_db_pools = { git = "https://github.com/rwf2/Rocket.git" } ``` -------------------------------- ### Diagnose Trait Bound Errors Source: https://github.com/rwf2/rocket/blob/master/docs/guide/14-faq.md Example of a compiler error indicating a missing trait implementation, often caused by dependency version mismatches. ```rust error[E0277]: the trait bound `Foo: Responder<'_, '_>` is not satisfied --> src\main.rs:4:20 | 4 | fn foo() -> Foo | ^^^ the trait `Responder<'_, '_>` is not implemented for `Foo` | = note: required by `respond_to` ``` -------------------------------- ### Configure NGINX reverse proxy Source: https://github.com/rwf2/rocket/blob/master/docs/guide/11-deploying.md Example NGINX configuration to proxy requests to the Rocket application, including header forwarding for IP and protocol. ```conf server { listen 80; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; } } ``` -------------------------------- ### Configure TLS Certificate and Key in Rocket.toml Source: https://github.com/rwf2/rocket/blob/master/docs/guide/10-configuration.md Specify the paths to your TLS certificate chain and private key in Rocket.toml to enable TLS. ```toml [default.tls] key = "path/to/key.pem" certs = "path/to/certs.pem" ``` -------------------------------- ### Create Test Client Source: https://github.com/rwf2/rocket/blob/master/docs/guide/09-testing.md Create a tracked client from a Rocket instance to dispatch requests. This client is used to generate local requests for testing. ```rust use rocket::local::blocking::Client; # let rocket = rocket::build(); let client = Client::tracked(rocket).unwrap(); # let _ = client; ``` -------------------------------- ### Generate Type-Safe URIs with uri! Source: https://context7.com/rwf2/rocket/llms.txt Demonstrates defining routes and generating URIs using the uri! macro with positional, named, and mounted parameters. ```rust #[macro_use] extern crate rocket; use rocket::response::Redirect; use rocket::form::Form; #[derive(FromForm, UriDisplayQuery)] struct UserQuery { name: String, age: Option, } #[get("/user//?")] fn user(id: usize, name: &str, age: Option) -> String { format!("User {}: {}, age: {:?}", id, name, age) } #[get("/search?")] fn search(query: UserQuery) -> String { format!("Searching for: {}, age: {:?}", query.name, query.age) } #[get("/redirect")] fn redirect_example() -> Redirect { // Type-safe URI generation Redirect::to(uri!(user(id = 42, name = "Alice", age = Some(25)))) } #[get("/search-redirect")] fn search_redirect() -> Redirect { let query = UserQuery { name: "Bob".to_string(), age: Some(30), }; Redirect::to(uri!(search(query = query))) } fn main() { // Compile-time checked URI generation let uri1 = uri!(user(101, "Mike Smith", Some(28))); assert_eq!(uri1.to_string(), "/user/101/Mike%20Smith?age=28"); // Named parameters (order doesn't matter) let uri2 = uri!(user(name = "Mike", id = 101, age = _)); assert_eq!(uri2.to_string(), "/user/101/Mike"); // With mount point let uri3 = uri!("/api", user(id = 1, name = "Test", age = None::)); assert_eq!(uri3.to_string(), "/api/user/1/Test"); } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![user, search, redirect_example, search_redirect]) } ``` -------------------------------- ### Recommended .dockerignore File Source: https://github.com/rwf2/rocket/blob/master/docs/guide/11-deploying.md A .dockerignore file to prevent unnecessary files and directories from being copied into the Docker build context, optimizing build times and image size. ```gitignore target .cargo **/*.sh **/*.tar.gz ``` -------------------------------- ### Define Database Connection Guard Source: https://github.com/rwf2/rocket/blob/master/contrib/sync_db_pools/README.md Use the `#[database(...)]` macro to define a Rocket request guard for your database connection. This example uses SQLite. ```rust #[macro_use] extern crate rocket; use rocket_sync_db_pools::{database, diesel}; #[database("sqlite_logs")] struct LogsDbConn(diesel::SqliteConnection); ``` -------------------------------- ### Configure Rocket Applications Source: https://context7.com/rwf2/rocket/llms.txt Shows how to use Figment to deserialize configuration into a struct and override settings via environment variables. ```rust #[macro_use] extern crate rocket; use rocket::serde::Deserialize; use rocket::fairing::AdHoc; use rocket::State; #[derive(Debug, Deserialize)] #[serde(crate = "rocket::serde")] struct AppConfig { api_key: String, max_connections: usize, debug_mode: bool, } #[get("/config")] fn show_config(config: &State) -> String { format!( "Max connections: {}, Debug: {}", config.max_connections, config.debug_mode ) } #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![show_config]) .attach(AdHoc::config::()) } // Rocket.toml: // [default] // address = "0.0.0.0" // port = 8000 // api_key = "secret-key" // max_connections = 100 // debug_mode = true // // [default.limits] // form = "64 kB" // json = "1 MiB" // // [release] // port = 80 // debug_mode = false // secret_key = "hPrYyЭRiMyµ5sBB1π+CMæ1køFsåqKvBiQJxBVHQk=" // Environment variables override config file: // ROCKET_PORT=9000 // ROCKET_API_KEY="env-secret" // ROCKET_DEBUG_MODE=false ``` -------------------------------- ### Handle Incoming Data Directly with `Data` Type Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Use the `Data` type to directly handle incoming data streams, for example, to stream data to a sink. ```rust use rocket::data::Data; #[post("/stream", data = "")] fn stream_data(raw_data: Data<'_>) { // Process raw_data stream here // For example, consume it: // let _ = raw_data.open().into_bytes().await; } ``` -------------------------------- ### Rust Function Spacing Source: https://github.com/rwf2/rocket/blob/master/CONTRIBUTING.md Always separate function items with one blank line. This applies to both 'Yes' and 'No' examples, illustrating the correct and incorrect spacing. ```rust fn foo() { // .. } fn bar() { // .. } ``` ```rust fn foo() { // .. } fn bar() { // .. } ``` -------------------------------- ### Bundle Rocket application for remote deployment Source: https://github.com/rwf2/rocket/blob/master/docs/guide/11-deploying.md Uses cargo-zigbuild to cross-compile the application and create a gzipped archive containing the binary and assets. ```sh ## configure these for your environment PKG="app" # cargo package name TARGET="x86_64-unknown-linux-gnu" # remote target ASSETS=("Rocket.toml" "static" "templates") # list of assets to bundle BUILD_DIR="target/${TARGET}/release" # cargo build directory ## ensure target toolchain is present rustup target add $TARGET ## cross-compile cargo zigbuild --target $TARGET --release ## bundle tar -cvzf "${PKG}.tar.gz" "${ASSETS[@]}" -C "${BUILD_DIR}" "${PKG}" ``` -------------------------------- ### Implement Paste Upload Logic Source: https://github.com/rwf2/rocket/blob/master/docs/guide/12-pastebin.md Full implementation of the upload route, including ID generation, file streaming with size limits, and URI construction. ```rust # #[macro_use] extern crate rocket; // We derive `UriDisplayPath` for `PasteId` in `paste_id.rs`: # use std::borrow::Cow; # use std::path::{Path, PathBuf}; # use rocket::request::FromParam; #[derive(UriDisplayPath)] pub struct PasteId<'a>(Cow<'a, str>); # impl PasteId<'_> { # pub fn new(size: usize) -> PasteId<'static> { todo!() } # pub fn file_path(&self) -> PathBuf { todo!() } # } # # impl<'a> FromParam<'a> for PasteId<'a> { # type Error = &'a str; # fn from_param(param: &'a str) -> Result { todo!() } # } // We implement the `upload` route in `main.rs`: use rocket::data::{Data, ToByteUnit}; use rocket::http::uri::Absolute; # use rocket::tokio::fs::File; // In a real application, these would be retrieved dynamically from a config. const ID_LENGTH: usize = 3; const HOST: Absolute<'static> = uri!("http://localhost:8000"); # #[get("/")] fn index() -> &'static str { "" } # #[get("/")] fn retrieve(id: PasteId<'_>) -> Option { todo!() } #[post("/", data = "")] async fn upload(paste: Data<'_>) -> std::io::Result { let id = PasteId::new(ID_LENGTH); paste.open(128.kibibytes()).into_file(id.file_path()).await?; Ok(uri!(HOST, retrieve(id)).to_string()) } ``` -------------------------------- ### Define the index route handler Source: https://github.com/rwf2/rocket/blob/master/docs/guide/12-pastebin.md Defines the handler for the root GET request ('/'). This route returns static text explaining how to use the pastebin service. ```rust # #[macro_use] extern crate rocket; #[get("/")] fn index() -> &'static str { "\ USAGE POST / accepts raw data in the body of the request and responds with a URL of a page containing the body's content GET / retrieves the content for the paste with id `` " } ``` -------------------------------- ### Initialize Rocket Template Fairing Source: https://github.com/rwf2/rocket/blob/master/docs/guide/06-responses.md Attach the template fairing to the Rocket instance to enable template rendering. ```rust #[macro_use] extern crate rocket; use rocket_dyn_templates::Template; #[launch] fn rocket() -> _ { rocket::build() .mount("/", routes![/* .. */]) .attach(Template::fairing()) } ``` -------------------------------- ### Declare a 404 Not Found Catcher Source: https://github.com/rwf2/rocket/blob/master/docs/guide/05-requests.md Use the `catch` attribute with the desired HTTP status code to declare a catcher. This example shows how to declare a catcher for 404 errors. ```rust # #[macro_use] extern crate rocket; # fn main() {} use rocket::Request; #[catch(404)] fn not_found(req: &Request) { /* .. */ } ```