Hastic standalone https://hastic.io
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.9 KiB

3 years ago
use hastic::services::user_service;
3 years ago
use warp::filters::method::post;
3 years ago
use warp::http::HeaderValue;
3 years ago
use warp::hyper::{Body, StatusCode};
use warp::{body, options, Rejection, Reply};
3 years ago
use warp::{http::Response, Filter};
3 years ago
3 years ago
mod auth;
3 years ago
3 years ago
use serde::Serialize;
3 years ago
use parking_lot::RwLock;
use std::sync::Arc;
3 years ago
#[derive(Serialize)]
3 years ago
pub struct Message {
3 years ago
message: String,
}
pub struct API {
user_service: Arc<RwLock<user_service::UserService>>,
}
3 years ago
3 years ago
impl API {
pub fn new() -> API {
API {
user_service: Arc::new(RwLock::new(user_service::UserService::new())),
}
3 years ago
}
3 years ago
fn json<T: Serialize>(t: &T) -> Response<Body> {
3 years ago
API::json_with_code(t, StatusCode::OK)
}
fn json_with_code<T: Serialize>(t: &T, status_code: StatusCode) -> Response<Body> {
3 years ago
let j = warp::reply::json(t);
let mut rs = j.into_response();
let hs = rs.headers_mut();
hs.insert("Access-Control-Allow-Origin", HeaderValue::from_static("*"));
3 years ago
hs.insert(
"Access-Control-Allow-Methods",
HeaderValue::from_static("POST, GET, OPTIONS, DELETE"),
);
hs.insert(
"Access-Control-Allow-Headers",
HeaderValue::from_static("*"),
);
3 years ago
*rs.status_mut() = status_code;
3 years ago
rs
}
pub async fn serve(&self) {
3 years ago
let not_found =
warp::any().map(|| warp::reply::with_status("Not found", StatusCode::NOT_FOUND));
let options = warp::any().and(options()).map(|| {
3 years ago
API::json(&Message {
3 years ago
message: "ok".to_owned(),
})
});
let login = auth::get_route(self.user_service.clone());
3 years ago
let public = warp::fs::dir("public");
3 years ago
println!("Start server on 8000 port");
3 years ago
// TODO: move it to "server"
let routes = login.or(options).or(public).or(not_found);
3 years ago
warp::serve(routes).run(([127, 0, 0, 1], 8000)).await;
3 years ago
}
3 years ago
}