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


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


  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.


Licensed under your option of:


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


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

Projects Using Gotham


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?.

  • Async static file serving

    Async static file serving

    On your blog, you say that some important features are on the roadmap, including async static file serving. Is there any work on that for the moment ?

    feature documentation help wanted 
    opened by tforgione 62
  • Import JWT Authentication middleware

    Import JWT Authentication middleware

    This PR imports the JWT Authentication middleware I was chatting about earlier in #289. The current version is set up to work with Gotham 0.3.

    opened by noisefloors 17
  • state: move instantiation into State::from_request

    state: move instantiation into State::from_request

    This refactors the service implementation a little bit to instantiate the State via a dedicated method. The underlying goal is to allow users to use Gotham without having to use its handler.

    The motivation for this is to let users inject more things into their state and call their handler directly instead of having to go through a Hyper service. In our case, we use this for:

    • Integrating in a Hyper service for a sub-route.
    • Injecting data about TLS client certificates that were used by the client
    feature discussion non-breaking-change 
    opened by krallin 16
  • Async Request Handlers by customizing error response

    Async Request Handlers by customizing error response

    /// # customize response for HandlerError /// ## Why do we need it? /// We might want to customize different response for different error, eg: /// * for authorized-user-resource, we might return 403(Forbidden) for an un-logged-in user; /// * or when some file user requesting is not found, we might return 404; /// * ... /// Or we just want to send with content-type: application/json when request is application/json. /// (In the old, we just send 500 with plain/text for any request if error happens)

    opened by darkdarkfruit 16
  • Migrate Gotham to std Futures to support Async/Await

    Migrate Gotham to std Futures to support Async/Await

    With the anticipated release of async-await in stable rust this week, I took an effort to migrate Gotham to run on std futures using the pre-release versions of the dependencies (tokio, hyper, etc).

    NOTE: This doesn't attempt to introduce await or async fn into the codebase (there was a single unavoidable case due to an tokio::File::metadata API change). That is designed as a future activity.

    This migration involved a few key efforts:

    1. Convert from Futures 0.1 to Futures-preview 0.3 (mostly Future<Item=> to Future<Output=Result<>>).
    2. Update dependencies to pre-release versions (tokio-0.2 and hyper-0.13). There's still other dependencies that are outstanding and blocking the full release.
    3. Migrate Handler trait to a pinned box HandlerFuture.

    This is a work-in-progress with a few blockers before this would be ready:

    Gotham Dependencies:

    • [x] Update Futures from futures-preview to futures = 0.3 when the other dependencies (hyper, tokio, etc) update in concert.
    • [x] Update Tokio to 0.2 from alpha pre-releases
    • [x] Update Hyper to 0.13 from alpha pre-releases
    • [x] Update Tower-Service to 0.3 from alpha pre-releases. Hyper is migrating many of its traits to tower-service::Service and so is now a direct dependency.
    • [x] Released version of futures_rustls which is currently a branch of tokio-rustls ported to Futures-preview
    • [x] Released version of futures-tokio-compat or suggested tokio::compat library for bridging futures::AsyncRead and tokio::AsyncRead. See https://github.com/tokio-rs/tokio/issues/1297 and https://github.com/async-rs/async-std/issues/54

    Middleware Dependencies:

    • [x] Diesel - Requires updated release of tokio-threadpool
    • [ ] JWT - Requires updated release of jsonwebtoken since it's dependency ring conflicts withs futures-rustls.

    The following examples were not updated (and thus commented out in Cargo.toml) due to incompatible dependencies:

    • [x] hello_world_until is dependent on a compatible version of tokio-signal
    • [x] diesel is dependent on the Diesel middleware
    • [ ] openssl is dependent on tokio-openssl
    • [ ] websocket is dependent on tokio-tungstenite
    opened by kevinastone 15
  • Add experimental Router builder API

    Add experimental Router builder API

    This is a first attempt at building the Router creation API that will be used by all Gotham applications.

    The primary goal of this branch is to get as far as we can without introducing any macros. Keeping in line with idiomatic Rust, I opted to write a "builder" API for the router. An simple example router with this API looks like:

    fn router() -> Router {
        // Note: Pipeline API isn't part of this PR
        let pipelines = new_pipeline_set();
        let (pipelines, default) =
        let pipelines = finalize_pipeline_set(pipelines);
        let default_pipeline_chain = (default, ());
        // Router builder starts here
        build_router(default_pipeline_chain, pipelines, |route| {
            route.scope("/api", |route| {

    More in-depth examples:

    This is an experimental API which will likely see some breaking changes before we're totally happy with it, ~~and so it will ship behind a Cargo feature ("experimental-router") to communicate that fact to app developers who might otherwise expect some stability in the API.~~

    As a future concern, once this API is bedded in and we know more about what we can't do with a builder API, we can look at adding macros. That's out of scope for this PR.

    Comments/questions/feedback/review welcome from anybody who's interested in doing so.

    feature discussion 
    opened by smangelsdorf 15
  • Implement IntoResponse for more type combinations

    Implement IntoResponse for more type combinations

    This fixes #277, kinda.

    This PR will introduce some new constructs for returning responses, namely:

    (Mime, Into<Body>)
    (StatusCode, Mime, Into<Body>)

    There are a few things to note:

    • We can't actually implement for Into<Body> due to clashes with Response<Body>, so they're manually derived for the meantime (somewhat annoying, but not the end of the world).
    • The default mime type is TEXT_PLAIN; not sure if it should be something else?
    • The default status code is OK.

    Each implementation just passes through to the next, and the actual response is built using the create_response function in the helper - to keep things consistent. I adjusted the signature there to align with the new types as well.

    The idea is that create_response is now only needed when you need to do something to the response itself manually; such as changing headers, and so on. If you only care about status/mime/body, you can just return a Tuple (which should theoretically work for a lot of cases).

    In doing all of this, the generic type B was removed from IntoResponse - which isn't breaking as it was introduced between 0.2.1 and now anyway. I think aligning on Body for the response body type makes sense at least for the time being.

    Finally I removed construct_response in favour of making create_empty_response the base response creator. I doubt there's much overhead to doing it this way, and even so it makes the code more readable so likely a non-issue.

    A few remaining questions I'd like opinions on:

    1. Given that the point of this is to discourage create_response directly, should I update all examples to use these new formats?
    2. Should create_response simply become a function that accepts State, IntoResponse? It can then just attach any default headers (etc.) onto the returned response.
    3. Is TEXT_PLAIN an appropriate default mime type?
    opened by whitfin 14
  • Add workers middleware and reengineer diesel middleware to make use of it

    Add workers middleware and reengineer diesel middleware to make use of it

    The best (read: laziest) way to describe this PR is by pointing at the documentation for the "workers" and "diesel" middleware as written for this PR (mostly the rustdoc).

    Ref #210

    opened by smangelsdorf 12
  • Add top-level function for starting a server with a provided Handle

    Add top-level function for starting a server with a provided Handle

    I would like to run two tokio-based servers in parallel in my application, one of which is a Gotham HTTP server. As far as my understanding of tokio goes, it ought to be possible to create one event loop and register both services onto it.

    Is there a way to start a Gotham server using a provided tokio Handle, rather than letting it create its own event loop? If not, and you feel that its a reasonable feature to implement, I'm happy to work on adding this behaviour.

    feature help wanted question 
    opened by kierdavis 12
  • Support graceful shutdown.

    Support graceful shutdown.

    This is a version of gotham-rs/gotham#223 updated for the current master branch.

    Fixes gotham-rs/gotham#220.

    opened by im-0 12
  • Update tokio-tungstenite requirement from 0.15 to 0.16

    Update tokio-tungstenite requirement from 0.15 to 0.16

    Updates the requirements on tokio-tungstenite to permit the latest version.


    Sourced from tokio-tungstenite's changelog.

    0.16.0 (Unreleased)

    • Add a function to allow to specify the TLS connector when using connect() like logic.
    • Add support for choosing the right root certificates for the TLS.
    • Change the behavior of the connect() so that it fails when using TLS without TLS feature.
    • Do not project with Unpin.
    • Update the dependencies with important implications / improvements.



    • Support for rustls as TLS backend.
      • The tls feature was renamed to native-tls and uses a OS-native TLS implementation.
      • A new native-tls-vendored feature that uses native-tls but forces to build a vendored version (mostly for openssl) instead of linking against the system installation.
      • New rustls-tls feature flag to enable TLS with rustls as backend.
      • stream::Stream was renamed to MaybeTlsStream and wraps a rustls TLS stream as well now.
      • If both native-tls and rustls-tls are enabled native-tls is used by default.
      • A new Connector was introduced that is similar to the previous TlsConnector but now allows to control the used TLS backend explicitly (or disable it) in client_async_tls_with_config.


    • Upgrade from Tokio 0.3 to Tokio 1.0.0.

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.

    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies breaking-change 
    opened by dependabot[bot] 1
  • Use futures::lock::Mutex for sharing state between requests

    Use futures::lock::Mutex for sharing state between requests

    Hi! I'm working with futures (i.e my handlers are async)

    Ofter I need to protect my Service around Arc<Mutex<_>> where Arc and Mutex came from std. But when you are working with futures, it's better to use futures::lock::Mutex in order to avoid dead lock (see for example https://users.rust-lang.org/t/std-mutex-vs-futures-mutex-vs-futures-lock-mutex-for-async/41710/2) So,

    use futures::lock::Mutex;
    use std::sync::{Arc};
    #[derive(Clone, StateData)]
    pub struct ChatServiceWrapper {
        pub inner: Arc<Mutex<ChatService>>,
        let chat_service = ChatServiceWrapper {
            inner: Arc::new(Mutex::new(ChatService::new())),
        let pipeline = new_pipeline()
            .add(StateMiddleware::new(chat_service)) // <--- this goes to error

    the error is

    the type `std::cell::UnsafeCell<chat_service::ChatService>` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary
    `std::cell::UnsafeCell<chat_service::ChatService>` may contain interior mutability and a reference may not be safely transferrable across a catch_unwind boundary
    help: within `rest_api::ChatServiceWrapper`, the trait `std::panic::RefUnwindSafe` is not implemented for `std::cell::UnsafeCell<chat_service::ChatService>`

    How can I fix this error??

    Thanks a lot

    opened by allevo 10
  • HandlerError with body data

    HandlerError with body data

    Maybe this should be done different, but I would assume that I can additionally to modify the status_code of the HandlerError also add body data. My use-case would be e.g.: parsing JSON data from the request and if there is a syntax error return the error message from serde(as body) with an UNPROCESSABLE_ENTITY status code.

    opened by rp- 2
  • Deconstruct State for handler functions

    Deconstruct State for handler functions

    Currently, all handler functions take either State or &State as their only parameter, and need to retrieve all information they need in user code. It would be more convenient if we allowed for syntax like this:

    route.get("/").to(|(headers, body): (HeaderMap, Body)| { /* create response */ })

    This was first suggested by @tanriol in the Gitter chat.

    proposal discussion 
    opened by msrd0 0
  • Make code to parse Accept-Encoding header public

    Make code to parse Accept-Encoding header public

    Gotham's to_file and to_dir methods internally handle compression and parsing the Accept-Encoding header. However, these methods cannot be used all the time, so it would be nice if we export the code to parse the Accept-Encoding header to extract the client-preferred compression.

    opened by msrd0 0
  • WIP: remove StateData trait

    WIP: remove StateData trait

    Closes #487.

    This PR is still WIP, because documentation has not been updated yet. If this RFC is accepted, I will update the related docs.

    refactor breaking-change 
    opened by lucacasonato 1
  • RFC: remove StateData trait

    RFC: remove StateData trait

    Currently to be able to store something in State, the data needs to implement the StateData trait. This StateData trait is really just an alias for Any + Send. It would be really nice if implementing this trait would not be needed. Here are some reasons why:

    1. Not technically needed. This abstraction is not actually needed. As you can see in this branch, the StateData can be removed and replaced with direct Any + Send without issues. There is thus no technical reason for the existence of this trait.
    2. Unnecessary boilerplate. To be able to store a struct in gotham::state::State, you need to either add the StateData proc-macro to the declaration, or manually implement gotham::state::StateData. This is an extra line of code that is not needed.
    3. Forces unnecessary wrapper structs. If you want to store a structure from a crate outside of yours in State, you need to wrap it with of a wrapper struct just so you can implement StateData. This adds unnecessary bloat.

    I propose that the StateData trait and StateData proc-macro are removed. All methods on State and FromState that currently take a StateData would take any Any + Send instead.

    More benefits:

    • This would also be one less thing that users need to learn about when starting out with Gotham.
    • Removes ~150 LOC from gotham and examples.
    proposal discussion breaking-change 
    opened by lucacasonato 4
  • make IntoResponse implementation more intuitive

    make IntoResponse implementation more intuitive

    As of right now, the IntoResponse for Result<T, E> just calls the IntoResponse implementation for either type. This is fine in most use cases, but is counter-intuitive when Err("API Error") generates a 200 response.

    Reported by @tanriol on gitter.

    discussion refactor breaking-change 
    opened by msrd0 1
  • Pass State into the Session Backend

    Pass State into the Session Backend

    I am working on a Redis backend for storing the session.

    The way to do this, I imagine, is to create a separate Middleware to manage a connection pool to Redis. This Middleware would store a connection in the State that the Session backend can use. I don't see any other way that the Redis connections could be handled, correct me if I'm wrong.

    In order for the backend to use the connection it needs to have access to the State. Currently, this isn't passed in. It would be great if it could be!

    I have knocked up a quick proof of concept here: https://github.com/FungusHumungus/gothamboogy/blob/master/src/redis.rs, and have a tentative pull request available - if you think this is the correct way to solve this issue. I'll submit it in a minute for your perusal.

    This is probably also relevant to #69.

    proposal help wanted discussion breaking-change 
    opened by StephenWakely 9
  • Example for new Accept router

    Example for new Accept router

    As of #424 we can match on multiple Accept types. The examples haven't yet been updated for this behavior yet, however.

    help wanted example non-breaking-change 
    opened by nyarly 0
  • gotham-0.7.1(Nov 18, 2021)

  • gotham-0.7.0(Nov 12, 2021)


    • gotham 0.7.0
    • gotham_derive 0.7.0
    • gotham_middleware_jwt 0.7.0
    • gotham_middleware_diesel 0.4.0

    Starting with this version, directly importing the derive macros from the gotham_derive crate is deprecated. Use gotham::prelude::* instead.


    • Send state to the session backend and allow it to return futures (#468)
    • Re-export the mime crate and all gotham_derive macros
    • Add AsyncTestServer (#552, #553, #555)
    • Introduce new features session, http2 and testing (all enabled by default)
    • Remove rustls feature from the default features
    • Start functions now return a result (#568, #571)
    • Allow access to the inner error of a HandlerError (#575)
    • Add a prelude module that re-exports traits and derive macros (#567)
    Source code(tar.gz)
    Source code(zip)
  • gotham-0.6.1(Jul 12, 2021)


    • gotham_middleware_jwt 0.6.1
    • gotham_middleware_diesel 0.3.1


    • Rename JWTMiddleware to JwtMiddleware
    • Update outdated documentation
    Source code(tar.gz)
    Source code(zip)
  • gotham-0.6.0(Mar 20, 2021)


    • gotham 0.6.0
    • gotham_derive 0.6.0
    • gotham_middleware_jwt 0.6.0
    • gotham_middleware_diesel 0.3.0


    • Update hyper to 0.14 and tokio to 1.0
    • Update cookie to 0.15
    • Implement Into<Response> for TestResponse
    • Add downcast_cause_ref and downcast_cause_mut for HandlerError
    • Add add_route_matcher to DelegateRouteBuilder
    • Add State::from_request to allow using gotham with a custom hyper service
    • Fix spurious Not Connected errors (#461)
    • Remove PathExtractor and QueryStringExtractor derive macros, they've been replaced by StateData and StaticResponseExtender a few releases ago
    Source code(tar.gz)
    Source code(zip)
  • borrow-bag-1.1.0(Mar 20, 2021)

  • 0.1.0(Aug 15, 2017)

    The initial release of the Gotham web framework.

    We wanted to get Gotham in the hands of the Rust community early with regular smaller iterations to follow.

    The Gotham 0.1 release includes the following features:

    • Handlers and Controllers
    • Advanced Routing
    • Type Safe Extractors
    • Middleware and Pipelines
    • Request State
    • Sessions
    • Request and Response helpers
    • Test helpers
    • Thoroughly documented code and the beginnings of a Gotham book
    Source code(tar.gz)
    Source code(zip)
A flexible web framework that promotes stability, safety, security and speed.
Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust.

Actix Web Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust Features Supports HTTP/1.x and HTTP/2 Streaming and pipelining

Actix 12.6k Nov 25, 2021
Sincere is a micro web framework for Rust(stable) based on hyper and multithreading

The project is no longer maintained! Sincere Sincere is a micro web framework for Rust(stable) based on hyper and multithreading. Style like koa. The

null 94 Oct 30, 2021
An Extensible, Concurrent Web Framework for Rust

Iron Extensible, Concurrency Focused Web Development in Rust. Response Timer Example Note: This example works with the current iron code in this repos

null 6k Nov 18, 2021
An expressjs inspired web framework for Rust

nickel.rs nickel.rs is a simple and lightweight foundation for web applications written in Rust. Its API is inspired by the popular express framework

null 2.9k Nov 26, 2021
A web framework for Rust.

Rocket Rocket is an async web framework for Rust with a focus on usability, security, extensibility, and speed. #[macro_use] extern crate rocket; #[g

Sergio Benitez 15.5k Nov 30, 2021
A lightweight web framework built on hyper, implemented in Rust language.

Sapper Sapper, a lightweight web framework, written in Rust. Sapper focuses on ergonomic usage and rapid development. It can work with stable Rust. Sa

Daogang Tang 617 Nov 18, 2021
Web framework in Rust

Rouille, a Rust web micro-framework Rouille is a micro-web-framework library. It creates a listening socket and parses incoming HTTP requests from cli

Pierre Krieger 734 Nov 25, 2021
A fast, boilerplate free, web framework for Rust

Tower Web A web framework for Rust with a focus on removing boilerplate. API Documentation Tower Web is: Fast: Fully asynchronous, built on Tokio and

Carl Lerche 963 Nov 17, 2021
Simple and fast web server

see Overview Simple and fast web server as a single executable with no extra dependencies required. Features Built with Tokio and Hyper TLS encryption

null 146 Nov 15, 2021
A starter template for actix-web projects that feels very Django-esque. Avoid the boring stuff and move faster.

Jelly A.K.A, the actix-web starter you probably wish you had. This is provided as-is, and anyone is free to extend it or rework it as they desire - ju

SecretKeys 101 Nov 22, 2021
Add Facebook and Google authentication to your HTTP REST API in Actix-web

I created this project while learning Rust. Project shows how to handle Facebook and Google token verification in Rust using Actix-Web. Hope this help

null 33 Nov 9, 2021
JSON Web Token implementation in Rust.

Frank JWT Implementation of JSON Web Tokens in Rust. Algorithms and features supported HS256 HS384 HS512 RS256 RS384 RS512 ES256 ES384 ES512 Sign Veri

Alex Maslakov 235 Nov 5, 2021
Source Code for 'Practical Rust Web Projects' by Shing Lyu

Apress Source Code This repository accompanies Practical Rust Web Projects by Shing Lyu (Apress, 2021). Download the files as a zip using the green bu

Apress 26 Nov 27, 2021
Extension for actix-web to validate user permissions

actix-web-grants Extension for actix-web to validate user permissions. To check user access to specific services, you can use built-in proc-macro, Per

Artem Medvedev 61 Nov 21, 2021
web browser as a language server

web-browser-lsp A toy program that implements a text-based web browser as a language server. Motivation My favorite progrmming tools are neovim, tmux

octaltree 10 Jun 12, 2021
[OUTDATED] A light HTTP framework for Rust

Rustful A light HTTP framework for Rust, with REST-like features. The main purpose of Rustful is to create a simple, modular and non-intrusive foundat

Erik Hedvall 869 Nov 28, 2021
REST-like API micro-framework for Rust. Works with Iron.

Table of Contents What is Rustless? Usage warning Basic Usage Complex example Mounting Parameters validation and coercion Use JSON Schema Query string

Rustless 605 Nov 2, 2021
Fully async-await http server framework

Saphir is a fully async-await http server framework for rust The goal is to give low-level control to your web stack (as hyper does) without the time

Richer Archambault 77 Nov 8, 2021
:zap: fast http framework for rust

zap ⚡ The mission of zap is, to deliver a basic, but fast rust web server library. Documentation About This code is based on tokio's minihttp project,

Daniel Oltmanns 53 Apr 10, 2021