diff --git a/README.md b/README.md index 6c66022..a79c73c 100644 --- a/README.md +++ b/README.md @@ -25,17 +25,21 @@ cargo add haro Then, on your main.rs: ```Rust -use haro::{Application, Request, Response}; +use haro::{Application, Request, Response, Handler}; use serde_json::json; fn main() { - let mut app = Application::new("0:8000"); - app.route("/", |_|Response::str("Hello Haro")); - app.route("/hello/:name", hello); + let mut app = Application::new("0:8080"); + let hello_handler = HelloHandler { + name: "Haro".to_string(), + }; + app.route("/", |_| Response::str("Hello Haro")); // route by closure + app.route("/input/:name", input); // route by function + app.route_handler("/hello", hello_handler); //route by `Handler` trait type app.run(); } -fn hello(req: Request) -> Response { +fn input(req: Request) -> Response { let data = json!({ "method":req.method(), "args":req.args, @@ -44,6 +48,16 @@ fn hello(req: Request) -> Response { }); Response::json(data) } + +struct HelloHandler { + name: String, +} + +impl Handler for HelloHandler { + fn call(&self, _: Request) -> Response { + Response::str(format!("hello {}", self.name)) + } +} ``` ```bash @@ -56,7 +70,7 @@ Hello Haro ``` ```bash -http post "localhost:8080/hello/world?a=b" c=d +http post "localhost:8080/input/world?a=b" c=d HTTP/1.1 200 OK content-length: 77 content-type: application/json diff --git a/examples/readme/main.rs b/examples/readme/main.rs new file mode 100644 index 0000000..c7837f4 --- /dev/null +++ b/examples/readme/main.rs @@ -0,0 +1,33 @@ +use haro::{Application, Handler, Request, Response}; +use serde_json::json; + +fn main() { + let mut app = Application::new("0:8080"); + let hello_handler = HelloHandler { + name: "Haro".to_string(), + }; + app.route("/", |_| Response::str("Hello Haro")); // route by closure + app.route("/input/:name", input); // route by function + app.route_handler("/hello", hello_handler); //route by `Handler` trait type + app.run(); +} + +fn input(req: Request) -> Response { + let data = json!({ + "method":req.method(), + "args":req.args, + "params":req.params, + "data":req.data, + }); + Response::json(data) +} + +struct HelloHandler { + name: String, +} + +impl Handler for HelloHandler { + fn call(&self, _: Request) -> Response { + Response::str(format!("hello {}", self.name)) + } +}