Giter VIP home page Giter VIP logo

sincere's Introduction

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();
});

sincere's People

Contributors

atul9 avatar danclive avatar nabijaczleweli avatar palfrey avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

sincere's Issues

为什么感觉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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.