Rocket is an async web framework for Rust with a focus on usability, security,

Visiting localhost:8000/hello/John/58, for example, will trigger the hello

Rocket

Rocket is an async web framework for Rust with a focus on usability, security, extensibility, and speed.

Visiting localhost:8000/hello/John/58, for example, will trigger the hello route resulting in the string Hello, 58 year old named John! being sent to the browser. If an <age> string was passed in that can't be parsed as a u8, the route won't get called, resulting in a 404 error.

Documentation

Rocket is extensively documented:

  • Overview: A brief look at what makes Rocket special.
  • Quickstart: How to get started as quickly as possible.
  • Getting Started: How to start your first Rocket project.
  • Guide: A detailed guide and reference to Rocket.
  • API Documentation: The "rustdocs".

The official community support channels are #rocket:mozilla.org on Matrix and the bridged #rocket IRC channel on Libera.Chat at irc.libera.chat. We recommend joining us on Matrix via Element. If your prefer IRC, you can join via the Kiwi IRC client or a client of your own.

Examples

An extensive number of examples are provided in the examples/ directory. Each example can be compiled and run with Cargo. For instance, the following sequence of commands builds and runs the Hello, world! example:

You should see Hello, world! by visiting http://localhost:8000.

Building and Testing

The core directory contains the three core libraries: lib, codegen, and http published as rocket, rocket_codegen and rocket_http, respectively. The latter two are implementations details and are reexported from rocket.

Testing

Rocket's complete test suite can be run with ./scripts/test.sh from the root of the source tree. The script builds and tests all libraries and examples in all configurations. It accepts the following flags:

  • --examples: tests all examples in examples/
  • --contrib: tests each contrib library and feature individually
  • --core: tests each core/lib feature individually
  • --benchmarks: runs all benchmarks
  • --all: runs all tests in all configurations

Additionally, a +${toolchain} flag, where ${toolchain} is a valid rustup toolchain string, can be passed as the first parameter. The flag is forwarded to cargo commands. Any other extra parameters are passed directly to cargo.

To test crates individually, simply run cargo test --all-features in the crate's directory.

Codegen Testing

Code generation diagnostics are tested using trybuild; tests can be found in the codegen/tests/ui-fail directories of respective codegen crates. Each test is symlinked into sibling ui-fail-stable and ui-fail-nightly directories which contain the expected error output for stable and nightly compilers, respectively. To update codegen test UI output, run a codegen test suite with TRYBUILD=overwrite and inspect the diff of .std* files.

Documentation

API documentation is built with ./scripts/mk-docs.sh. The resulting assets are uploaded to api.rocket.rs.

Documentation for a released version ${x} can be found at https://api.rocket.rs/v${x} and https://rocket.rs/v${x}. For instance, the documentation for 0.4 can be found at https://api.rocket.rs/v0.4 and https://rocket.rs/v0.4. Documentation for unreleased versions in branch ${branch} be found at https://api.rocket.rs/${branch} and https://rocket.rs/${branch}. For instance, the documentation for the master branch can be found at https://api.rocket.rs/master and https://rocket.rs/master. Documentation for unreleased branches is updated periodically.

Contributing

Contributions are absolutely, positively welcome and encouraged! Contributions come in many forms. You could:

  1. Submit a feature request or bug report as an issue.
  2. Ask for improved documentation as an issue.
  3. Comment on issues that require feedback.
  4. Contribute code via pull requests.

We aim to keep Rocket's code quality at the highest level. This means that any code you contribute must be:

  • Commented: Complex and non-obvious functionality must be properly commented.
  • Documented: Public items must have doc comments with examples, if applicable.
  • Styled: Your code's style should match the existing and surrounding code style.
  • Simple: Your code should accomplish its task as simply and idiomatically as possible.
  • Tested: You must write (and pass) convincing tests for any new functionality.
  • Focused: Your code should do what it's supposed to and nothing more.

All pull requests are code reviewed and tested by the CI. Note that unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Rocket by you shall be dual licensed under the MIT License and Apache License, Version 2.0, without any additional terms or conditions.

License

Rocket is licensed under either of the following, at your option:

  • Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
  • MIT License (LICENSE-MIT or #404)

The Rocket website source is licensed under separate terms.

Issues

Collection of the latest Issues

SergioBenitez

SergioBenitez

suggestion
0

We need to test that the server terminates successfully (Rocket::launch() returns) even when there's:

  • Runaway I/O via spawn_blocking().
  • Infinite responder.
  • Infinite handler.
  • Stalling client.
sLINK1337

sLINK1337

suggestion
2

Hello i got some Problems with my Page, i can't use the Register there is a problem i don't know how i can get it to work.

"Error: Captcha validation failed, please try again."

and on the Server i get this Message

=> Error: No matching routes for OPTIONS /api/v2/auth/register. => Warning: Responding with 404 Not Found catcher. => CORS Fairing: Turned missing route OPTIONS /api/v2/auth/register into an OPTIONS pre- flight request => Response succeeded. POST /api/v2/auth/register application/json: => Matched: POST /api/v2/auth/register application/json (register) sending request POST https://www.google.com/recaptcha/api/siteverify => Outcome: Success => Response succeeded.

i tried everything but nothing works, so maybe someone here in the Community can help me with the Problem.

christian-oudard

christian-oudard

triage
4

Description

When multiple requests are using the same SQLite database, they error out with the message DatabaseError(__Unknown, "database is locked"). This only happens when there is a transaction going, and the same table is being updated by multiple requests.

To Reproduce

Here is a pretty minimal example of the problem: https://github.com/christian-oudard/rust_tutorial/tree/0edcd03dd5b92926790d93be57bf996c4a339627/rocket_tutorial

Expected Behavior

The busy_timeout setting of SQLite should be respected here, and make the threads block until the database is available.

Environment:

  • OS Distribution and Kernel: Ubuntu 21.10
  • Rocket Version: 0.4.10

Additional Context

This seems to be a Diesel or R2D2 problem, but the usage pattern is a very common one among web apps. Using write-ahead-logging and setting the busy timeout don't work.

somehowchris

somehowchris

request
2

Since @SergioBenitez is returning, imma pin that one here https://github.com/rocket-org/Rocket/issues/18 @Cloudef

Is your feature request motivated by a concrete problem? Please describe.

Currently the serde::msgpack::MsgPack included with rocket only does "compact serialization", meaning it doesn't serialize key names, only values in arrays. To be JSON compatible, and to avoid bugs it would be nice to have "named serialization".

Why this feature can't or shouldn't live outside of Rocket

The serde::msgpack is already in rocket.

Ideal Solution

It seems the problem is here: https://github.com/Rocket-org/Rocket/blob/cc0621626bf5e917ea1d4c1e29a327e9a7871921/core/lib/src/serde/msgpack.rs#L191 This should be changed to rmp_serde::to_vec_named, however since I'm still fairly new to rust, I don't know how this would be exposed so that the developer can choose either from the compact or named serialization form.

inferiorhumanorgans

inferiorhumanorgans

triage
3

Description

With rocket 0.5.0-rc.1, a route defined as:

#[get("/route", format="image/webp")]

  • Does not match when the Accept header is set to text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8

  • Does not match when the Accept header is set to text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/avif,*/*;q=0.8

  • Does not match when the Accept header is set to text/html,application/xhtml+xml,application/xml,image/webp;q=0.9,image/avif,image/webp,*/*;q=0.8

  • Does match with the Accept header set to: image/webp,text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8

  • Does match with the Accept header set to: image/webp

  • Does match with the Accept header set to: */*

To Reproduce

Define a route e.g.

Expected Behavior

All of the above values for the accept header should match the route. The first variant is the value that my copy of Firefox sends out. I'm not clear on what preferred means in the Rocket documentation, but I'd assume at the very least that having image/webp anywhere the higher (0.9) q value should match.

My goal is to be able to respond with a webp image if it exists locally and is supported by the user agent.

roy-ganz

roy-ganz

request
0

Hi, currently rocket_db_pools supports MySQL through sqlx.

The mysql_async crate features a Pool and could be supported for users who don't want an extra sqlx dependency.

I've done this for myself here and think others might want that, too.

So my proposal is to add MySQL to the supported drivers

Thanks for your time.

ijackson

ijackson

request
1

When using derive, it is often useful to be able to make common structs that contain fields where everything can be done automatically, and then surrounding structs where only some of the things are derived.

To do this, one needs to indicate to each derive macro that the fields of a contained struct should be imported without another level of nesting. #[serde(flatten)], #[row(flatten)]. But unfortunately there is not a #[field(flatten)].

For example, I have this in a work-in-progress webapp:

This doesn't work because the generated code expects form submissions containing common.email but the actual form contains only email.

Alternatives Considered

Letting the fields be nested the way FromForm wants doesn't really work, because whether a field ends up in common depends not on anything principled about the system, but simply on whether the automatic handling produced by the derive macros is appropriate.

For now I have to just give up on making this part of my code common, and writing some boilerplate to copy fields from one struct to another.

Additional Context

I'm not convinced that field is a good name for this attribute. Derive macro inert attributes are in a global namespace. I suggest that form would be better. However, it is perhaps too late to change this now.

Flying-Toast

Flying-Toast

request
2

Rocket has validation for Forms (rocket::form::validate), but when accepting other body content (e.g. JSON), there is no way to validate fields of the Deserialized object, e.g.

Polygons shouldn't be allowed to have less than 3 sides, but there is no simple way to enforce this. Ideally we could do something similar to form validation, with field attributes.

Why this feature can't or shouldn't live outside of Rocket

This could possibly be implemented outside of Rocket using some Validate derive and a Valid<T> guard that will only pass if validation succeeds, but that is less than ideal.

Ideal Solution

Ideally, the form-validation logic could be pulled out into its own independent trait, so that you can derive it on any type:

cataggar

cataggar

request
4

I want to be be able to test that routes resolve correctly, given the HTTP method and URI.

Existing Functionality

Router

Suggested Changes

The above code works if Router is made public #1873 and the route name is settable #1872.

Alternatives Considered

Additional Context

ralpha

ralpha

enhancement
4

Description

When testing my code I want to be able to test out my API endpoint, but not keep the changes in the database. I can do this in Diesel by using conn.begin_test_transaction(). But to use this with rocket is fairly complicated right now. Some small changes could make this much easier to do. The code below is based on a bunch of thing, including this: https://github.com/diesel-rs/diesel/issues/2733

How could it work (does not work currently)

But this does not work because of either Poolable or diesel::PgConnection needs to be implemented in the current crate. So to get around this you can always implement your own object and use that. Like this:

But this does not work because of the following constraint: type Manager: ManageConnection<Connection=Self>; This constraint is reasonable in most cases but does not allow for a different struct in these cases. If this constraint could be removed or be made generic then this would allow for custom poolable connections.

This would make it much easier to implement this. Right now you have to manually implement #[rocket_contrib::database("databasename")] And re-implement functions like run, fairing, get, ... and FromRequest. So this is about 250 lines of code instead of the 28 from above.

It would be a very welcome change. I can create a MR for this if this is something that you would like to see added.

Environment:

  • OS Distribution and Kernel: any
  • Rocket Version: 0.5.0-rc.1
ssendev

ssendev

suggestion
5

Existing Functionality

I want to ship a single file without a templates directory.

One way it is possible now is to use a managed state Tera instance but this requires changing the routes which means it is not possible to have templates included in release and reloaded from files during development.

With rocket.attach(Template::custom(… it is possible to cfg!(debug_assertions) engines.tera.add_raw_template("index.html", include_str!("../templates/index.html.tera")). This works but still requires an empty templates folder to be present.

(Well it almost works. Since rocket strips two extensions and templates added with add_raw_template only one template names aren't the same in debug and release. Fortunaltely it is possible to create symlinks from index.html.html.tera to index.html.tera and then one can use index.html as template name)

Suggested Changes

Add Template::fully_custom which uses Tera::default instead of Tera::new

Alternatives Considered

  • I tried engines.tera = Tera::default() but that didn't have any effect.

  • Adding engines.clear_config() which would reset the Tera instance to its Tera::defalt() state and could be called in Template::custom

  • Ideally there would be a Template::compiled_in_fairing() which would behave like Template::fairing but load templates at compile time but this might be hard to implement.

Full example

gustavowd

gustavowd

question
1

Hi Sergio,

I'm loving the rocket so far. I'm trying to create a REST API for a protocol known as IEEE 2030.5. This protocol uses this content type on its header: Content-Type: application/sep+xml

However, when i try to use something like this: #[post("/dcap/edev//di", format = "application/sep+xml", data = "<user_input>")]

I get this warning: "'application/sep+xml' is not a known media type"

Is it possible to add this media type to rocket?

Also, the protocol is based on a RESP API + xml + xml schema. Is there any plan to add xml serialize support to rocket?

Finally, the post messages should be anwsered with a HTTP/1.1 204 No Content message. I was able to return a 204 message, but the content lenght is suposed to be 0. However, with rocket i received this: < HTTP/2 204 < server: Rocket < x-frame-options: SAMEORIGIN < x-content-type-options: nosniff < permissions-policy: interest-cohort=() < date: Sun, 20 Jun 2021 02:34:25 GMT

On a commercial REST API server i received this: < HTTP/1.1 204 No Content < Content-Length: 0 < Date: Sun, 20 Jun 2021 02:35:13 GMT

Is it possible to return a Content-Length: 0 HTTP/1.1 204 No Content message?

Thanks in advance, Gustavo Denardin

ijackson

ijackson

enhancement
3

Hi. I'm upgrading one of my applications from Rocket 0.4 to 0.5. I am having a little trouble converting my custom FromFormValue to FromFormField.

My old code is roughly like this:

With Rocket 0.5 I'm to impl FromFormField which means I have to return a rocket::form::Error. The rocket::form::Error does not seem to have a way to record the desired HTTP status response, and hence control the return value from form::Error::status.

(Please forgive me if I have missed a way to do this; I looked in the api docs for form::Error and FromFormField and also the relevant-seeming sections of the guide, searching both for "form" and "error".)

I want to control the http status because I am using a form guard in circumstances where I sometimes want to say 404 if the guard fails, and sometimes even 403.

I don't think this can be fixed easily without a breaking change to at least one of rocket::form::Error or ErrorKind so it would be good to fix this before Rocket 0.5.0.

I think the best fix is probably to add a new variant to ErrorKind, or to expand Custom, something like this:

or this:

I wonder if ErroKind ought to be marked #[non_exhaustive] for future-proofing.

SergioBenitez

SergioBenitez

enhancement
4

A common use-case is streaming data from a client to file storage in the cloud. For instance, a file upload that is destined to be stored in Amazon S3. To prevent users from needlessly writing to disk, the TempFile guard does not implement AsyncRead: if the disk is not the final destination, it is likely the wrong tool. This forces the user to rethink their strategy (#1646, #1661), a good thing, at the expense of needing to write a custom data or form guard to accomplish their ultimate task.

We should remove this expense by proving data guards (i.e, S3File, AzureFile, etc) that stream directly to common cloud storage. To do so, we'd need to answer the following questions:

  • Where would this functionality live?
  • Which HTTP client would we use?
  • How would timeouts and limits for outbound requests/responses be configured?
  • How would we handle credentials?
  • Besides Amazon/Azure/Google, are there other big providers we should support?
  • Besides an object identifier, what other information should the guards expose?
SergioBenitez

SergioBenitez

enhancement
6

Testing forms in Rocket is currently an entirely manual process:

With the addition of multipart form support, form testing verbosity is even further exacerbated:

Rocket should make testing applications with forms a much simpler task.

Here's how we might hope testing the above forms would look:

An API enabling this might resemble:

Versions

Find the latest versions by id

v0.5.0-rc.2 - May 09, 2022

See the CHANGELOG, news article, migration guide, and FAQ for more information.

v0.5.0-rc.1 - Jun 09, 2021

See the CHANGELOG and news article for more information.

v0.4.10 - May 22, 2021

See the CHANGELOG for more information.

v0.4.9 - May 19, 2021

See the CHANGELOG for more information.

v0.4.8 - May 19, 2021

See the CHANGELOG for more information.

v0.4.7 - Feb 10, 2021

See the CHANGELOG for more information.

v0.4.6 - Nov 17, 2020

See the CHANGELOG for more information.

v0.4.5 - May 30, 2020

See the CHANGELOG for more information.

v0.4.4 - Mar 09, 2020

See the CHANGELOG for more information.

v0.4.3 - Mar 01, 2020

See the CHANGELOG for more information.

v0.4.2 - Jun 29, 2019

See the CHANGELOG for more information.

v0.4.1 - May 11, 2019

See the CHANGELOG for more information.

v0.4.0 - Dec 08, 2018

See the CHANGELOG and news article for more information.

v0.4.0-rc.2 - Dec 01, 2018

See the CHANGELOG and news article for more information.

v0.4.0-rc.1 - Oct 31, 2018

See the CHANGELOG and news article for more information.

v0.3.17 - Sep 30, 2018

See the CHANGELOG for more information.

v0.3.16 - Aug 24, 2018

See the CHANGELOG for more information.

v0.3.15 - Jul 16, 2018

See the CHANGELOG for more information.

v0.3.14 - Jun 23, 2018

See the CHANGELOG for more information.

v0.3.13 - Jun 15, 2018

See the CHANGELOG for more information.

v0.3.12 - May 31, 2018

See the CHANGELOG for more information.

v0.3.11 - May 20, 2018

See the CHANGELOG for more information.

v0.3.10 - May 05, 2018

See the CHANGELOG for more information.

v0.3.9 - Apr 27, 2018

See the CHANGELOG for more information.

v0.3.8 - Apr 07, 2018

See the CHANGELOG for more information.

v0.3.7 - Apr 04, 2018

See the CHANGELOG for more information.

v0.3.6 - Jan 13, 2018

See the CHANGELOG for more information.

v0.3.5 - Dec 18, 2017

See the CHANGELOG for more information.

v0.3.4 - Dec 14, 2017

See the CHANGELOG for more information.

v0.3.3 - Sep 26, 2017

See the CHANGELOG for more information.

Information - Updated May 25, 2022

Stars: 17.3K
Forks: 1.2K
Issues: 70

An fast and intuitive rust web framework

built with async/await in mind

An fast and intuitive rust web framework

Example application and boiler plate code for Rust, Actix and Heroku

Actix is a popular Rust web framework and these examples get your feet wet

Example application and boiler plate code for Rust, Actix and Heroku

Rust web application

Diesel (ORM) is used to work with the database

Rust web application

Audioserve is an audio and audio book server with a simple setup

Simple and easy to use audio and audiobook Rust web platform written in Rust

Audioserve is an audio and audio book server with a simple setup
Http

799

Rouille, a Rust web micro-framework

Rouille is a micro-web-framework library

Rouille, a Rust web micro-framework

Rust-WebSocket is a WebSocket (RFC6455) library written in Rust

Rust-WebSocket is a WebSocket (crates

Rust-WebSocket is a WebSocket (RFC6455) library written in Rust

Rust Websocket Physics Playground

A multiplayer physics playground, written in rust, using tokio-tungstenite for websockets and rapier-rs for physics

Rust Websocket Physics Playground

Rust WebAssembly A* Pathfinding Demo

This is a port of an A* implementation of mine from an old Unity maze project

Rust WebAssembly A* Pathfinding Demo

Create a ALB in AWS

Make it point to a lambda called rust-web (needed by deploy

Create a ALB in AWS

Base web app for Rust web projects

Started with the static_index example here:

Base web app for Rust web projects

Simple Rust Web Service

This is the readme file for a Medium article I published on creating a

Simple Rust Web Service

Rust Web assembly game 1024

The game logic has been developed by Rust Programming Language

Rust Web assembly game 1024
Facebook Instagram Twitter GitHub Dribbble
Privacy