Convert Figma logo to code with AI

rwf2 logoRocket

A web framework for Rust.

24,163
1,552
24,163
52

Top Related Projects

24,163

A web framework for Rust.

21,219

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

18,202

Ergonomic and modular web framework built with Tokio, Tower, and Hyper

2,233

A flexible web framework that promotes stability, safety, security and speed.

6,130

An Extensible, Concurrent Web Framework for Rust

An expressjs inspired web framework for Rust

Quick Overview

Rocket is a web framework for Rust that makes it simple to write fast, secure web applications without sacrificing flexibility, usability, or type safety. It provides a robust set of features including JSON serialization, templating, and database integration, all while leveraging Rust's safety guarantees and performance.

Pros

  • Strong type safety and compile-time checks
  • Excellent performance due to Rust's efficiency
  • Intuitive routing system with type-safe request handling
  • Built-in templating engine and JSON support

Cons

  • Steeper learning curve for developers new to Rust
  • Smaller ecosystem compared to more established web frameworks
  • Can be verbose for simple tasks due to Rust's strict typing
  • Limited middleware support compared to some other frameworks

Code Examples

  1. Basic route handling:
#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}
  1. JSON handling with derived structs:
#[derive(Serialize, Deserialize)]
struct Task {
    id: usize,
    description: String,
}

#[post("/tasks", data = "<task>")]
fn create_task(task: Json<Task>) -> Json<Task> {
    // Process the task...
    task
}
  1. Database integration with Diesel:
#[get("/users/<id>")]
async fn get_user(conn: DbConn, id: i32) -> Option<Json<User>> {
    conn.run(move |c| {
        users::table
            .find(id)
            .first::<User>(c)
            .map(Json)
            .ok()
    }).await
}

Getting Started

To get started with Rocket, add it to your Cargo.toml:

[dependencies]
rocket = "0.5.0-rc.2"

Then, create a basic "Hello, world!" application:

#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

Run your application with cargo run and visit http://localhost:8000 in your browser.

Competitor Comparisons

24,163

A web framework for Rust.

Pros of Rocket

  • More active development with recent commits
  • Larger community and contributor base
  • Better documentation and examples

Cons of Rocket

  • Potentially less stable due to frequent changes
  • May have a steeper learning curve for beginners
  • Larger codebase could lead to increased complexity

Code Comparison

Rocket:

#[get("/hello/<name>")]
fn hello(name: &str) -> String {
    format!("Hello, {}!", name)
}

Rocket>:

#[get("/hello/{name}")]
fn hello(name: String) -> String {
    format!("Hello, {}!", name)
}

The main difference in the code snippets is the syntax for route parameters. Rocket uses angle brackets <>, while Rocket> uses curly braces {}. Additionally, Rocket> uses String instead of &str for the name parameter.

Both frameworks offer similar functionality for creating web applications in Rust, but Rocket has a more established ecosystem and community support. Rocket> may be more suitable for those looking for a simpler or more experimental approach. Ultimately, the choice between the two depends on specific project requirements and developer preferences.

21,219

Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

Pros of Actix-web

  • Higher performance and lower resource usage
  • More flexible and customizable architecture
  • Better support for asynchronous programming

Cons of Actix-web

  • Steeper learning curve and more complex API
  • Less opinionated, requiring more manual configuration
  • Fewer built-in features and conveniences

Code Comparison

Actix-web:

use actix_web::{web, App, HttpResponse, HttpServer};

async fn index() -> HttpResponse {
    HttpResponse::Ok().body("Hello world!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(web::resource("/").to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

Rocket:

#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

Both Actix-web and Rocket are popular Rust web frameworks, but they have different design philosophies. Actix-web focuses on performance and flexibility, while Rocket prioritizes developer experience and ease of use. The code comparison shows that Rocket has a more concise and declarative syntax, while Actix-web offers more explicit control over the application structure.

18,202

Ergonomic and modular web framework built with Tokio, Tower, and Hyper

Pros of Axum

  • Built on top of Tokio, providing excellent async performance and scalability
  • Modular design allows for easy composition of handlers and middleware
  • Supports both low-level and high-level APIs, offering flexibility for different use cases

Cons of Axum

  • Steeper learning curve, especially for developers new to async Rust
  • Less opinionated than Rocket, requiring more manual configuration
  • Smaller ecosystem and community compared to Rocket

Code Comparison

Axum route definition:

async fn hello() -> &'static str {
    "Hello, World!"
}

let app = Router::new().route("/", get(hello));

Rocket route definition:

#[get("/")]
fn hello() -> &'static str {
    "Hello, World!"
}

rocket::build().mount("/", routes![hello])

Summary

Axum and Rocket are both popular Rust web frameworks, each with its strengths. Axum excels in performance and flexibility, leveraging Tokio's async runtime. It offers a modular approach, allowing developers to compose handlers and middleware easily. However, it has a steeper learning curve and requires more manual configuration.

Rocket, on the other hand, provides a more opinionated and user-friendly experience, with a focus on developer ergonomics. It has a larger ecosystem and community support but may be less flexible in certain scenarios.

The choice between Axum and Rocket depends on project requirements, team expertise, and performance needs.

2,233

A flexible web framework that promotes stability, safety, security and speed.

Pros of Gotham

  • Focuses on asynchronous programming, potentially offering better performance for I/O-bound applications
  • Provides a more flexible routing system with support for dynamic route segments
  • Offers a plugin system for extending functionality and middleware support

Cons of Gotham

  • Less mature and smaller community compared to Rocket
  • Fewer built-in features and conveniences out of the box
  • Steeper learning curve, especially for developers new to asynchronous programming

Code Comparison

Rocket example:

#[get("/hello/<name>")]
fn hello(name: &str) -> String {
    format!("Hello, {}!", name)
}

Gotham example:

fn hello(state: State) -> (State, Response<Body>) {
    let name = state.borrow::<PathExtractor<String>>().unwrap().0.clone();
    let response = format!("Hello, {}!", name);
    (state, Response::builder().body(response.into()).unwrap())
}

Both frameworks offer routing capabilities, but Rocket's syntax is more concise and declarative. Gotham's approach is more explicit and provides finer control over the request and response handling process.

6,130

An Extensible, Concurrent Web Framework for Rust

Pros of Iron

  • More lightweight and minimalistic, offering greater flexibility for custom implementations
  • Faster compilation times due to its simpler architecture
  • Easier to understand and modify for developers who prefer a bare-bones approach

Cons of Iron

  • Less feature-rich out of the box compared to Rocket
  • Requires more manual configuration and setup for common web development tasks
  • Smaller community and ecosystem, potentially leading to fewer resources and third-party integrations

Code Comparison

Rocket example:

#[macro_use] extern crate rocket;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
}

Iron example:

extern crate iron;

use iron::prelude::*;
use iron::status;

fn main() {
    Iron::new(|_: &mut Request| {
        Ok(Response::with((status::Ok, "Hello, world!")))
    }).http("localhost:3000").unwrap();
}

Both examples demonstrate a simple "Hello, world!" web server, but Rocket's syntax is more declarative and uses attribute macros, while Iron's approach is more explicit and functional.

An expressjs inspired web framework for Rust

Pros of Nickel

  • Simpler and more lightweight, focusing on basic web server functionality
  • Easier to get started with for beginners or small projects
  • More flexible routing system with support for regex patterns

Cons of Nickel

  • Less feature-rich compared to Rocket's comprehensive ecosystem
  • Smaller community and fewer available plugins/extensions
  • Less actively maintained, with fewer recent updates

Code Comparison

Nickel route example:

fn hello_world(_: &mut Request) -> String {
    "Hello World".to_string()
}

server.get("/", hello_world);

Rocket route example:

#[get("/")]
fn hello_world() -> &'static str {
    "Hello World"
}

rocket::build().mount("/", routes![hello_world])

Both frameworks offer straightforward routing, but Rocket's approach is more declarative with its attribute-based routing system. Nickel uses a more traditional function-based approach, which may be more familiar to developers coming from other web frameworks.

Rocket provides a more comprehensive set of features out of the box, including built-in JSON serialization, form handling, and database integration. Nickel, on the other hand, focuses on simplicity and flexibility, allowing developers to add functionality as needed.

Overall, Rocket is better suited for larger, more complex applications, while Nickel may be preferable for simpler projects or those requiring a lightweight web server.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Rocket

Build Status Rocket Homepage Current Crates.io Version Matrix: #rocket:mozilla.org

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

#[macro_use] extern crate rocket;

#[get("/<name>/<age>")]
fn hello(name: &str, age: u8) -> String {
    format!("Hello, {} year old named {}!", age, name)
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/hello", routes![hello])
}

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:

Documentation for the master branch is available at https://rocket.rs/master and https://api.rocket.rs/master.

Documentation for major release version ${x} is available at https://[api.]rocket.rs/v${x}. For example, the v0.4 docs are available at https://rocket.rs/v0.4 and https://api.rocket.rs/v0.4.

Finally, API docs for active git branches are available at https://api.rocket.rs/${branch}. For example, API docs for the master branch are available at https://api.rocket.rs/master. Branch rustdocs are built and deployed on every commit.

Examples

The examples directory contains complete crates that showcase Rocket's features and usage. Each example can be compiled and run with Cargo. For instance, the following sequence of commands builds and runs the hello example:

cd examples/hello
cargo run

Getting Help

If you find yourself needing help outside of the documentation, you may:

Contributing

Contributions are absolutely, positively welcomed and encouraged! If you're interested in contributing code, please first read CONTRIBUTING for complete guidelines. Additionally, 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. Answers questions in GitHub discussions questions.
  5. Share a project in GitHub discussions show & tell.

License

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

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.

The Rocket website docs are licensed under separate terms. Any contribution intentionally submitted for inclusion in the Rocket website docs by you shall be licensed under those terms.