Convert Figma logo to code with AI

gotham-rs logogotham

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

2,233
125
2,233
53

Top Related Projects

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

9,488

A super-easy, composable, web server framework for warp speeds.

24,163

A web framework for Rust.

6,130

An Extensible, Concurrent Web Framework for Rust

An expressjs inspired web framework for Rust

Quick Overview

Gotham is a flexible web framework for Rust that emphasizes type safety, ergonomics, and speed. It provides a modular architecture that allows developers to build robust and scalable web applications with ease, leveraging Rust's powerful type system and performance characteristics.

Pros

  • Strong focus on type safety and compile-time checks
  • Modular design allowing for easy customization and extension
  • High performance due to Rust's efficiency and zero-cost abstractions
  • Comprehensive documentation and examples for quick learning

Cons

  • Steeper learning curve compared to some other web frameworks
  • Smaller community and ecosystem compared to more established frameworks
  • May be overkill for simple web applications or microservices
  • Requires understanding of Rust's ownership and borrowing concepts

Code Examples

  1. Basic "Hello, World!" handler:
use gotham::state::State;

fn say_hello(state: State) -> (State, &'static str) {
    (state, "Hello, World!")
}

fn main() {
    let addr = "127.0.0.1:7878";
    println!("Listening for requests at http://{}", addr);
    gotham::start(addr, || Ok(say_hello))
}
  1. Handling path parameters:
use gotham::state::State;
use gotham::handler::IntoResponse;
use gotham::helpers::http::response::create_response;
use gotham::router::builder::*;
use gotham::hyper::{Body, Response, StatusCode};

fn user_handler(state: State) -> (State, impl IntoResponse) {
    let user_id = state.borrow::<gotham::state::FromState>().unwrap();
    let response = create_response(
        &state,
        StatusCode::OK,
        mime::TEXT_PLAIN,
        format!("User ID: {}", user_id),
    );
    (state, response)
}

fn router() -> Router {
    build_simple_router(|route| {
        route.get("/user/:id").to(user_handler);
    })
}

fn main() {
    let addr = "127.0.0.1:7878";
    println!("Listening for requests at http://{}", addr);
    gotham::start(addr, router())
}
  1. Middleware example:
use gotham::handler::HandlerFuture;
use gotham::middleware::Middleware;
use gotham::state::State;

#[derive(Clone, NewMiddleware)]
struct TimingMiddleware;

impl Middleware for TimingMiddleware {
    fn call<Chain>(self, state: State, chain: Chain) -> HandlerFuture
    where
        Chain: FnOnce(State) -> HandlerFuture,
    {
        let start = std::time::Instant::now();
        let f = chain(state);
        f.map(move |(state, response)| {
            let duration = start.elapsed();
            println!("Request took: {:?}", duration);
            (state, response)
        })
    }
}

// Use in router: pipeline.add(TimingMiddleware::new());

Getting Started

To start using Gotham, add it to your Cargo.toml:

[dependencies]
gotham = "0.7.1"

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

use gotham::state::State;

fn say_hello(state: State) -> (State, &'static str) {
    (state, "Hello, World!")
}

fn main() {
    let addr = "127.0.0.1:7878";
    println!("Listening for requests at http://{}", addr);
    gotham::start(addr, || Ok(say_hello))
}

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

Competitor Comparisons

21,219

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

Pros of Actix-web

  • Higher performance and scalability, consistently ranking among the fastest web frameworks in benchmarks
  • More mature ecosystem with a larger community, resulting in better documentation and more third-party libraries
  • Built-in support for WebSockets and HTTP/2

Cons of Actix-web

  • Steeper learning curve due to its actor-based architecture and more complex API
  • Historically had some safety concerns due to extensive use of unsafe code (though this has been addressed in recent versions)

Code Comparison

Actix-web:

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

async fn hello() -> impl Responder {
    "Hello, World!"
}

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

Gotham:

use gotham::state::State;

fn say_hello(state: State) -> (State, &'static str) {
    (state, "Hello, World!")
}

fn main() {
    let addr = "127.0.0.1:8080";
    println!("Listening for requests at http://{}", addr);
    gotham::start(addr, || Ok(say_hello))
}

Both frameworks offer similar functionality, but Actix-web's async nature is more apparent in its code structure.

18,202

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

Pros of Axum

  • More active development and larger community support
  • Built on top of Tokio, providing excellent async performance
  • Modular design with a focus on composability and extensibility

Cons of Axum

  • Steeper learning curve for beginners due to its more complex architecture
  • Less opinionated, which may require more decision-making from developers

Code Comparison

Axum:

use axum::{
    routing::get,
    Router,
};

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(|| async { "Hello, World!" }));
    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

Gotham:

use gotham::state::State;

fn say_hello(state: State) -> (State, &'static str) {
    (state, "Hello, World!")
}

pub fn main() {
    let addr = "0.0.0.0:7878";
    println!("Listening for requests at http://{}", addr);
    gotham::start(addr, || Ok(say_hello))
}

Both frameworks offer similar functionality, but Axum's code is more concise and leverages async/await syntax. Gotham's approach is more traditional and may be easier for newcomers to understand. Axum's design allows for more flexibility in composing complex applications, while Gotham provides a simpler, more straightforward API for basic use cases.

9,488

A super-easy, composable, web server framework for warp speeds.

Pros of Warp

  • Lightweight and fast, with excellent performance benchmarks
  • Simple and intuitive API, making it easy to get started quickly
  • Strong focus on composability, allowing for modular and reusable code

Cons of Warp

  • Less comprehensive feature set compared to Gotham
  • Smaller ecosystem and community support
  • May require more manual implementation for certain advanced features

Code Comparison

Warp example:

use warp::Filter;

let hello = warp::path!("hello" / String)
    .map(|name| format!("Hello, {}!", name));

warp::serve(hello).run(([127, 0, 0, 1], 3030)).await;

Gotham example:

use gotham::router::builder::*;
use gotham::state::State;

fn say_hello(state: State) -> (State, String) {
    let name = state.borrow::<RouterData>().params().get("name").unwrap();
    (state, format!("Hello, {}!", name))
}

let router = build_simple_router(|route| {
    route.get("/hello/:name").to(say_hello);
});

gotham::start("127.0.0.1:3030", router).unwrap();

Both frameworks offer concise routing and handling, but Warp's API is generally more compact and functional in style, while Gotham provides a more traditional approach with explicit state management.

24,163

A web framework for Rust.

Pros of Rocket

  • More mature and widely adopted, with a larger community and ecosystem
  • Offers a simpler, more intuitive API with less boilerplate code
  • Provides built-in templating and form handling features

Cons of Rocket

  • Requires nightly Rust compiler, which may introduce instability
  • Less flexible for complex routing scenarios compared to Gotham
  • Higher compile times due to extensive use of macros

Code Comparison

Rocket:

#[macro_use] extern crate rocket;

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

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

Gotham:

use gotham::router::builder::*;
use gotham::state::State;

fn say_hello(state: State) -> (State, &'static str) {
    (state, "Hello, world!")
}

pub fn main() {
    let addr = "127.0.0.1:7878";
    let router = build_simple_router(|route| {
        route.get("/").to(say_hello);
    });

    gotham::start(addr, router)
}

Both frameworks aim to simplify web development in Rust, but Rocket focuses on developer ergonomics and ease of use, while Gotham emphasizes flexibility and performance. Rocket's syntax is more concise, but Gotham offers more control over routing and middleware. The choice between them depends on project requirements and developer preferences.

6,130

An Extensible, Concurrent Web Framework for Rust

Pros of Iron

  • More mature and established project with a larger community
  • Simpler and more straightforward API for basic web applications
  • Extensive middleware ecosystem for added functionality

Cons of Iron

  • Less active development and maintenance in recent years
  • Fewer built-in features compared to Gotham's more comprehensive approach
  • Performance may be slightly lower due to older design patterns

Code Comparison

Iron:

fn hello_world(_: &mut Request) -> IronResult<Response> {
    Ok(Response::with((status::Ok, "Hello World!")))
}

Iron::new(hello_world).http("localhost:3000").unwrap();

Gotham:

fn say_hello(state: State) -> (State, Response<Body>) {
    let res = create_response(&state, StatusCode::OK, mime::TEXT_PLAIN, "Hello World!");
    (state, res)
}

gotham::start("127.0.0.1:7878", || Ok(say_hello))

Both frameworks offer concise ways to create simple web applications, but Gotham's approach is more focused on state management and type safety. Iron's syntax is more straightforward for basic use cases, while Gotham provides a more structured foundation for complex applications.

An expressjs inspired web framework for Rust

Pros of Nickel

  • Simpler and more intuitive API, making it easier for beginners to get started
  • Better documentation and more examples available
  • More active community and frequent updates

Cons of Nickel

  • Less flexible and customizable compared to Gotham's modular architecture
  • May not perform as well as Gotham for complex, high-performance applications
  • Fewer advanced features out of the box

Code Comparison

Nickel example:

#[macro_use] extern crate nickel;

use nickel::Nickel;

fn main() {
    let mut server = Nickel::new();
    server.utilize(router! {
        get "**" => |_req, _res| "Hello world!"
    });
    server.listen("127.0.0.1:6767").unwrap();
}

Gotham example:

use gotham::state::State;

fn say_hello(state: State) -> (State, &'static str) {
    (state, "Hello World!")
}

pub fn main() {
    let addr = "127.0.0.1:7878";
    println!("Listening for requests at http://{}", addr);
    gotham::start(addr, || Ok(say_hello))
}

Both frameworks offer simple ways to create a basic web server, but Nickel's syntax is more concise and easier to understand at first glance. Gotham's approach is more modular and allows for greater flexibility in handling requests and responses.

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

The Gotham web framework

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

Join the chat at https://gitter.im/gotham-rs/gotham GitHub actions Dependency status

Features

  1. Stability focused. All releases target stable Rust. This will never change. To ensure future compatibility, we also run automated builds against Rust beta and nightly releases.
  2. Statically typed. The Gotham web framework is statically typed ensuring your application is correctly expressed at compile time.
  3. Async everything. By leveraging the Tokio project, all Gotham web framework types are async out of the box. Our async story is further enhanced by Hyper, a fast server that provides an elegant layer over stringly typed HTTP.
  4. Blazingly fast. Measure completed requests, including the 99th percentile, in µs.

License

Licensed under your option of:

Community

The following policies guide participation in our project and our community:

Learning

The following resources are available to assist you learning the Gotham web framework:

Projects Using Gotham

Alternatives

We hope you'll find the Gotham web framework is flexible enough to meet the needs of any web application you might like to build. Please have a chat with us or create an issue if you find this isn't the case, perhaps there is something the Gotham web framework can offer that will help you achieve your goals.

We do acknowledge that sometimes the choices we've made for the Gotham web framework may not suit the needs of all projects. If that is the case for your project there are alternative Rust web frameworks you might like to consider:

  1. Actix-Web
  2. Conduit
  3. Nickel
  4. Rocket
  5. Rouille

Explore even more suggestions at Are we web yet?.