118 lines
2.8 KiB
Rust
118 lines
2.8 KiB
Rust
// #![recursion_limit="2048"]
|
|
|
|
#[macro_use]
|
|
extern crate gotham_derive;
|
|
|
|
use std::sync::{Arc, Mutex};
|
|
use gotham::{
|
|
handler::assets::FileOptions,
|
|
router::builder::{DefineSingleRoute, DrawRoutes},
|
|
middleware::state::StateMiddleware,
|
|
pipeline::single::single_pipeline,
|
|
pipeline::single_middleware,
|
|
router::builder::*,
|
|
};
|
|
use std::io::Cursor;
|
|
use gotham::{
|
|
helpers::http::response::create_response,
|
|
hyper::{Body, Response},
|
|
state::{FromState, State},
|
|
};
|
|
use geo::{Rect, Point};
|
|
use serde::Deserialize;
|
|
|
|
mod area;
|
|
mod trees;
|
|
|
|
#[derive(Clone, StateData)]
|
|
pub struct AppState {
|
|
pub db: Arc<Mutex<postgres::Client>>,
|
|
}
|
|
|
|
|
|
#[derive(Debug, Deserialize, StateData, StaticResponseExtender)]
|
|
pub struct IdExtractor {
|
|
pub id: String,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize, StateData, StaticResponseExtender)]
|
|
pub struct AreaExtractor {
|
|
x1: f64,
|
|
y1: f64,
|
|
x2: f64,
|
|
y2: f64,
|
|
}
|
|
|
|
impl AreaExtractor {
|
|
fn grow(&self, a: f64) -> Self {
|
|
AreaExtractor {
|
|
x1: self.x1 - a * self.w(),
|
|
y1: self.y1 - a * self.h(),
|
|
x2: self.x2 + a * self.w(),
|
|
y2: self.y2 + a * self.h(),
|
|
}
|
|
}
|
|
|
|
fn to_rect(&self) -> Rect<f64> {
|
|
Rect::new((self.x1, self.y1), (self.x2, self.y2))
|
|
}
|
|
|
|
fn w(&self) -> f64 {
|
|
self.x2 - self.x1
|
|
}
|
|
|
|
fn h(&self) -> f64 {
|
|
self.y2 - self.y1
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Deserialize, StateData, StaticResponseExtender)]
|
|
pub struct PointExtractor {
|
|
x: f64,
|
|
y: f64,
|
|
}
|
|
|
|
impl PointExtractor {
|
|
fn to_point(&self) -> Point<f64> {
|
|
Point::new(self.x, self.y)
|
|
}
|
|
}
|
|
|
|
|
|
fn main() {
|
|
const DB_URL: &str = "host=10.233.1.2 dbname=treeadvisor user=treeadvisor password=123";
|
|
|
|
let db = postgres::Client::connect(DB_URL, postgres::NoTls)
|
|
.expect("DB");
|
|
|
|
let state = AppState {
|
|
db: Arc::new(Mutex::new(db)),
|
|
};
|
|
let (chain, pipelines) = single_pipeline(
|
|
single_middleware(
|
|
StateMiddleware::new(state)
|
|
)
|
|
);
|
|
let router = build_router(chain, pipelines, |route| {
|
|
route.get("/heatmap/:x1/:y1/:x2/:y2")
|
|
.with_path_extractor::<AreaExtractor>()
|
|
.to(trees::get_heatmap);
|
|
route.get("/area/:x/:y")
|
|
.with_path_extractor::<PointExtractor>()
|
|
.to(area::get_details);
|
|
route.get("/trees/:x1/:y1/:x2/:y2")
|
|
.with_path_extractor::<AreaExtractor>()
|
|
.to(trees::get_trees);
|
|
route.get("/tree/:id")
|
|
.with_path_extractor::<IdExtractor>()
|
|
.to(trees::get_tree);
|
|
route.get("static/*").to_dir(
|
|
FileOptions::new(&"static")
|
|
.with_cache_control("no-cache")
|
|
.with_gzip(true)
|
|
.build()
|
|
);
|
|
});
|
|
gotham::start("0.0.0.0:8400", router);
|
|
}
|