Crate swim

source Β·
Expand description

An opinionated batteries-included approach to a rust web framework.

The idea is to take the best parts of the rust ecosystem and combine them into a framework that is easy to use and provides a good developer experience.

Installation

Add the following to your Cargo.toml file.

[dependencies]
swim = "0.2"

Features

  • Go blazingly fast with hyper and tokio
  • Powerful routing with routerify
  • CLI tooling with cargo-swim (coming soon)
  • Database support with SeaORM (planned)
  • Templating with Tera (planned)
  • Dependency injection (planned)

Building a project

You define a project by defining a struct that implements the Project trait. It is the highest-level abstraction in the framework. It is responsible for defining the settings, apps, and middleware for your project.

β“˜
use swim::prelude::*;

struct MyProject;

impl Project for MyProject {
    fn settings(&self) -> Settings {
        Settings::builder()
            .extend_ron(relative! ("settings.ron"))
            .build()
    }

    fn apps(&self) -> Vec<Box<dyn App>> {
        vec! [
            MyApp.into()
        ]
    }

    fn middleware(&self) -> Vec<Box<dyn Middleware>> {
        vec! [
            MyMiddleware.into()
        ]
    }
}

Building apps

You define an app by defining a struct that implements the App trait. It is responsible for defining the routes and views for your app.

β“˜
use swim::prelude::*;

struct MyApp;

impl App for MyApp {
    fn mount(&self) -> &'static str {
        "/"
    }

    fn config(&self) -> AppConfig {
        AppConfig::with_name("MyApp")
    }

    fn models(&self) -> Vec<Box<dyn Model>> {
        vec! []
    }

    fn routes(&self) -> Vec<Route> {
        vec! [
            Route::new("/", IndexView),
            Route::new("/hello", HelloView),
            Route::new("/greeting/:name", GreetingView),
        ]
    }
}

Building views

You define a view by defining a struct that implements the View trait. It is responsible for handling the request and returning a response. You can implement the specific HTTP methods you want to handle.

β“˜
#[derive(Debug)]
pub struct HelloView;

#[async_trait::async_trait]
impl View for HelloView {
    async fn get(&self, request: Request<Body>) -> Result<Response<Body>> {
        Ok(Response::builder()
            .status(StatusCode::OK)
            .body(Body::from("Say hello to Swim! "))
            .unwrap())
    }

    async fn post(&self, request: Request<Body>) -> Result<Response<Body>> {
        Ok(Response::builder()
            .status(StatusCode::OK)
            .body(Body::from("It's a post request! "))
            .unwrap())
    }
}

Defining middlewares

You define a middleware by defining a struct that implements the Middleware trait. It is responsible for handling the request and returning a response. You can implement the specific HTTP methods you want to handle.

β“˜
#[derive(Debug)]
pub struct Logger;

#[async_trait::async_trait]
impl Middleware for Logger {
    async fn pre(&self, request: Request<Body>) -> Result<Request<Body>> {
        println! ("New request: {:?}", request.uri());

        Ok(request)
    }

    async fn post(&self, response: Response<Body>) -> Result<Response<Body>> {
        println! ("Response: {:?}", response.status());

        Ok(response)
    }
}

Running the project

You may use the elegant swim macro to run your project.

β“˜
#[tokio::main(flavor = "multi_thread")]
async fn main() {
    swim! (MyProject, host = "localhost", port = 8000);
}

Re-exports

pub use swim_core::async_trait;
pub use swim_core::hyper;
pub use swim_core::routerify;

Modules

Prelude for the swim crate.
Various utilities that are helpful while building a Swim application.

Macros

A macro to simplify the creation of a new Swim instance.

Structs

AppConfig stores the configuration for each App.
The CoreSettings struct holds basic, yet essential information about the application.
The DatabaseSettings struct holds information about the database connection.
A route is a mapping between a path and a view.
The Settings struct is used to configure the application.
The Swim struct is the main entry point for a Swim application.

Enums

Swim error type.

Traits

The App trait is implemented to divide a project into modular units referred to as apps.
The Middleware trait is implemented by middleware structs.
The Project trait is implemented by the main application struct.
Implement this trait to create a view.

Type Definitions

A type alias for a hyper request body.
A type alias for a hyper request.
A type alias for a hyper response.
Convinience Result type for the swim crate.
A type alias for a hyper status code.