use http::Method;
use micro_web::encoding::encoder::EncodeDecorator;
use micro_web::extract::{Form, Json};
use micro_web::router::filter::header;
use micro_web::router::{get, post, Router};
use micro_web::{RequestContext, Server};
use serde::Deserialize;
#[allow(dead_code)]
#[derive(Deserialize, Debug)]
pub struct User {
name: String,
zip: String,
}
async fn simple_get(method: &Method, str: Option<String>, str2: Option<String>) -> String {
println!("receive body: {}, {}", str.is_some(), str2.is_some());
format!("receive from method: {}\r\n", method)
}
async fn simple_handler_form_data(method: &Method, Form(user): Form<User>) -> String {
format!("receive from method: {}, receive use: {:?}\r\n", method, user)
}
async fn simple_handler_json_data(method: &Method, Json(user): Json<User>) -> String {
format!("receive from method: {}, receive use: {:?}\r\n", method, user)
}
async fn simple_handler_post(method: &Method, str: Option<String>, str2: Option<String>) -> String {
println!("receive body: {:?}, {:?}", str, str2);
format!("receive from method: {}\r\n", method)
}
async fn simple_another_get(method: &Method, str: Option<String>, str2: Option<String>) -> String {
println!("receive body: {:?}, {:?}", str, str2);
format!("receive from method: {}\r\n", method)
}
async fn get_request_context(req_cxt: &RequestContext<'_, '_> ) -> String {
println!("receive req context: {:?}", req_cxt);
"It works".to_owned()
}
async fn default_handler() -> &'static str {
"404 not found"
}
#[tokio::main]
async fn main() {
let router = Router::builder()
.route("/", get(simple_get))
.route(
"/",
post(simple_handler_form_data)
.with(header(http::header::CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref())),
)
.route("/", post(simple_handler_json_data).with(header(http::header::CONTENT_TYPE, mime::APPLICATION_JSON.as_ref())))
.route("/", post(simple_handler_post))
.route("/4", get(simple_another_get))
.route("/5", get(get_request_context))
.route("/6", get(async || { "it works"} ))
.with_global_decorator(EncodeDecorator)
.build();
Server::builder().router(router).bind("127.0.0.1:8080").default_handler(default_handler).build().unwrap().start().await;
}