Sincere is a micro web framework for Rust(stable) based on hyper and multithreading

Overview

The project is no longer maintained!

Sincere

crates.io Build Status MIT licensed Released API docs

Sincere is a micro web framework for Rust(stable) based on hyper and multithreading. Style like koa. The same, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. Sincere does not bundle any middleware within core, and provides an elegant suite of methods that make writing servers fast and enjoyable. Here is an example of a simple application:

extern crate sincere;

use sincere::App;

fn main() {
    let mut app = App::new();

    app.get("/", |context| {
        context.response.from_text("Hello world!").unwrap();
    });

    app.run("127.0.0.1:8000").unwrap();
}

Don't forget add this to your Cargo.toml:

[dependencies]
sincere = "0.7.0-alpha.1"

Build and run, then, visiting http://127.0.0.1:8000/, you will see Hello world on the screen.

API documentation:

Guide

Routing

app.add("GET", "/user", ...);

app.get("/user", ...);

app.get("/user/{id:[0-9]+}", ...);

app.post("/user", ...);

app.put("/user/{id:[0-9]+}", ...);

app.delete("/user/{id:[0-9]+}", ...);

app.options("/", ...);

app.connect("/", ...);

app.head("/", ...);

Route Group

use sincere::App;
use sincere::Group;

fn main() {
    let mut app = App::new();

    app.get("/", |context| {
        context.response.from_text("Hello world!").unwrap();
    });

    let mut user_group = Group::new("/user");

    // /user
    user_group.get("/", ...);
    // /user/123
    app.get("/{id:[0-9]+}", ...);

    app.mount_group(user_group::handle);

    app.run("127.0.0.1:8000");
}
use sincere::App;
use sincere::Group;
use sincere::Context;

pub struct User;

impl User {
    pub fn list(mut context: &mut Context) {
        ...
    }

    pub fn detail(mut context: &mut Context) {
        ...
    }

    pub fn handle() -> Group {
        let mut group = Group::new("/user");

        group.get("/", Self::list);
        group.get("/{id:[0-9]+}", Self::detail);

        group
    }
}

fn main() {
    let mut app = App::new();

    app.get("/", |context| {
        context.response.from_text("Hello world!").unwrap();
    });

    app.mount(User::handle());

    app.run("127.0.0.1:8000");
}

Middleware

use sincere::App;

fn main() {
    let mut app = App::new();

    app.begin(|context| {
        ...
    });

    app.before(|context| {
        ...
    });

    app.after(|context| {
        ...
    });

    app.finish(|context| {
        ...
    });


    app.get("/", |context| {
        context.response.from_text("Hello world!").unwrap();
    });

    app.run("127.0.0.1:8000");
}
...
app.begin(...).begin(...);

app.begin(...).finish(...);

app.begin(...).before(...).after(...).finish(...);
...
app.get("/", |context| {
    context.response.from_text("Hello world!").unwrap();
}).before(...).after(...);
let mut group = Group::new("/user");

group.before(...).after(...);

group.get("/", |context| {
    context.response.from_text("Hello world!").unwrap();
}).before(...).after(...);
pub fn auth(context: &mut Context) {
    if let Some(token) = context.request.get_header("Token") {
        match token::verify_token(token) {
            Ok(id) => {
                context.contexts.insert("id".to_owned(), Value::String(id));
            },
            Err(err) => {
                context.response.from_text("").unwrap();
                context.stop();
            }
        }
    } else {
        context.response.status_code(401);
        context.stop();
    }
}

app.post("/article", ...).before(auth);

group.post("/", ...).before(auth);
pub fn cors(app: &mut App) {

    app.begin(move |context| {
        if context.request.method() == &Method::Options {
            context.response
            .status_code(204)
            .header(("Access-Control-Allow-Methods", "GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS"));

            context.stop();
        }
    });

    app.finish(move |context| {
        context.response
        .header(("Access-Control-Allow-Origin", "*"))
        .header(("Access-Control-Allow-Headers", "content-type, token"));
    });
}

app.use_middleware(cors);

Path Parameters

app.get("/user/{id}", |context| {
    let id = context.request.param("id").unwrap();
});

app.get("/user/{id:[0-9]+}", |context| {
    let id = context.request.param("id").unwrap();
});

app.get("/user/{id:[a-z0-9]{24}}", |context| {
    let id = context.request.param("id").unwrap();
});

Query Parameters

/article?per_page=10&page=1

app.get("/article", |content| {
    let page = context.request.query("page").unwrap_or("1");
    let per_page = context.request.query("per_page").unwrap_or("10");
});

Bind Json

serde_derive = "1.0"

[dependencies.serde_json]
version = "1.0"
features = ["preserve_order"]
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
app.post("/article", |content| {

    #[derive(Deserialize, Debug)]
    struct New {
        title: String,
        image: Vec<String>,
        content: String
    }

    let new_json = context.request.bind_json::<New>().unwrap();

    // some code

    let return_json = json!({
        "article_id": 123
    });

    context.response.from_json(return_json).unwrap();
});

Get and set headers, http status code

app.get("/", |context| {
    let token = context.request.header("Token").unwrap_or("none".to_owned());

    context.response.from_text("Hello world!").status_code(200).header(("Hello", "World")).unwrap();
});
You might also like...
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

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

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

The light web framework for Rust.
The light web framework for Rust.

Rusty Web Rusty web is a simple to use, fully customizable lightweight web framework for rust developers. Learn rusty web Installation [dependencies]

Handlebars middleware for Iron web framework

handlebars-iron Handlebars middleware for the Iron web framework. This library, together with handlebars, iron and hyper, works on both stable and nig

simple static file server written in Rust based on axum framework

static-server simple static file server written in Rust based on axum framework I'm learning Rust and axum. My thought is simple. axum has a static-fi

Archibald is my attempt at learning Rust and writing a HTTP 1.1 web server.
Archibald is my attempt at learning Rust and writing a HTTP 1.1 web server.

Archibald To be a butler, is to be able to maintain an even-temper, at all times. One must have exceptional personal hygiene and look sharp and profes

VRS is a simple, minimal, free and open source static web server written in Rust
VRS is a simple, minimal, free and open source static web server written in Rust

VRS is a simple, minimal, free and open source static web server written in Rust which uses absolutely no dependencies and revolves around Rust's std::net built-in utility.

A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. :zap::crab:
A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. :zap::crab:

binserve ⚡ 🦀 A blazingly fast static web server with routing, templating, and security in a single binary you can set up with zero code. 🔥 UPDATE: N

Comments
  • 为什么感觉sincere性能不高

    为什么感觉sincere性能不高

    测试代码: https://github.com/dollarkillerx/sincere_examples 测试环境: RUST: rustc 1.46.0 (04488afe3 2020-08-24) GO: go version go1.15.2 linux/amd64 cpu: e5-2650 8c Mem: 8G SSD

    Sincere

    release opt-level = 3

    ~$  go-wrk -c 80 -d 5 http://127.0.0.1:8000/hello
    Running 5s test @ http://127.0.0.1:8000/hello
      80 goroutine(s) running concurrently
    94571 requests in 4.912792899s, 10.01MB read
    Requests/sec:		19249.95
    Transfer/sec:		2.04MB
    Avg Req Time:		4.155855ms
    Fastest Request:	132.482µs
    Slowest Request:	23.611864ms
    Number of Errors:	0
    

    GO Gin

    ~$ go-wrk -c 80 -d 5 http://127.0.0.1:8081/hello
    Running 5s test @ http://127.0.0.1:8081/hello
      80 goroutine(s) running concurrently
    181092 requests in 4.904672597s, 19.17MB read
    Requests/sec:		36922.34
    Transfer/sec:		3.91MB
    Avg Req Time:		2.166709ms
    Fastest Request:	86.728µs
    Slowest Request:	35.10243ms
    Number of Errors:	0
    
    

    GO Erguotou

    ~$ go-wrk -c 80 -d 5 http://127.0.0.1:8081/hello
    Running 5s test @ http://127.0.0.1:8081/hello
      80 goroutine(s) running concurrently
    205570 requests in 4.832811717s, 25.08MB read
    Requests/sec:		42536.31
    Transfer/sec:		5.19MB
    Avg Req Time:		1.880745ms
    Fastest Request:	72.469µs
    Slowest Request:	32.684381ms
    Number of Errors:	0
    
    opened by dollarkillerx 1
  • pin-project-lite needs Rust 1.37

    pin-project-lite needs Rust 1.37

    This uses tokio 0.2, which needs pin-project-lite at least version 0.1.1, which needs Rust 1.37.

    ... and as it turns out the tokio bytes work needs 1.39. See https://github.com/tokio-rs/bytes/issues/323

    opened by palfrey 0
Owner
null
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 610 Jan 4, 2023
Node.js http server framework powered by Hyper native binding.

hnsjs POC project. Install this test package yarn add @hnsjs/core Support matrix node10 node12 node14 node15 Windows x64 ✓ ✓ ✓ ✓ Windows x32 ✓ ✓ ✓ ✓

LongYinan 18 Nov 23, 2022
A synchronous HTTP server built on hyper.

Astra Astra is a synchronous HTTP server built on top of hyper. use astra::{Body, Response, Server}; fn main() { Server::bind("localhost:3000")

Ibraheem Ahmed 23 Nov 27, 2022
Static Web Server - a very small and fast production-ready web server suitable to serve static web files or assets

Static Web Server (or SWS abbreviated) is a very small and fast production-ready web server suitable to serve static web files or assets.

Jose Quintana 496 Jan 2, 2023
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 16.3k Jan 8, 2023
Salvo is a powerful and simplest web server framework in Rust world

Salvo is an extremely simple and powerful Rust web backend framework. Only basic Rust knowledge is required to develop backend services.

Salvo 1.2k Jan 5, 2023
A flexible web framework that promotes stability, safety, security and speed.

A flexible web framework that promotes stability, safety, security and speed. Features Stability focused. All releases target stable Rust. This will n

Gotham 2.1k Jan 3, 2023
A toy web framework inspired by gin-gonic/gin and expressjs/express.

Rum Framework A toy web framework inspired by gin-gonic/gin and expressjs/express. Installation Just add rum_framework to the dependencies of Cargo.to

Hidetomo Kou(YingZhi 2 Dec 20, 2022
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 6.1k Dec 27, 2022
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 3k Jan 3, 2023