This commit is contained in:
Dmitry Belyaev 2019-08-19 18:40:34 +03:00
parent a7b1233a0c
commit d97b820363
Signed by: b4tman
GPG Key ID: 41A00BF15EA7E5F3
3 changed files with 28 additions and 40 deletions

View File

@ -19,6 +19,8 @@ lmdb-zero="0.4"
rand="0.7"
env_logger = "0.6"
tera = "0.11"
# actix="0.7"
# tokio="0.1"
# futures="0.1"
[profile.release]
opt-level = 3
debug = false
lto = true

View File

@ -1,4 +1,3 @@
// extern crate actix;
extern crate actix_files;
extern crate actix_web;
extern crate serde;
@ -6,7 +5,6 @@ extern crate serde;
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate ledb;
#[macro_use]
extern crate ledb_derive;
@ -17,29 +15,14 @@ extern crate tera;
use tera::Context;
// extern crate futures;
// extern crate tokio;
use actix_web::{
error, guard, http::header, http::Method, middleware::Logger, middleware::NormalizePath, web,
App, Error, HttpRequest, HttpResponse, HttpServer, Responder, Result,
guard, http::header, middleware::Logger, web,
App, Error, HttpRequest, HttpResponse, HttpServer, Result,
};
use std::cell::Cell;
use rand::seq::IteratorRandom;
use std::time::Instant;
use std::{fs, io};
// use tokio::spawn;
// use futures::{Future};
// use actix::Actor;
// use actix::System;
//use crate::tokio::prelude::Future;
//use ledb_actix::{Document, Options, Storage, StorageAddrExt};
use ledb::{Options, Storage};
@ -126,8 +109,8 @@ fn get_question(storage: &Storage, id: u32) -> Result<Option<Question>, Error> {
return Ok(None);
}
let collection = storage.collection("questions").unwrap();
let last_id = collection.last_id().unwrap();
let collection = storage.collection("questions").expect("collection questions");
let last_id = collection.last_id().expect("questions last id");
if id > last_id {
Err(Error::from(()))
@ -154,7 +137,7 @@ fn show_question_details(template_file: &str, data: web::Data<AppState>, id: web
let body = data.template.render(template_file, &question).unwrap();
Ok(HttpResponse::Ok().content_type("text/html").body(body))
} else {
Ok(HttpResponse::Found()
Ok(HttpResponse::PermanentRedirect()
.header(header::LOCATION, "/q/")
.finish())
}
@ -175,15 +158,15 @@ fn show_answer(data: web::Data<AppState>, id: web::Path<u32>) -> Result<HttpResp
show_question_details("answer.html", data, id)
}
fn index(data: web::Data<AppState>, req: HttpRequest) -> Result<HttpResponse, Error> {
let collection = data.storage.collection("questions").unwrap();
fn index(data: web::Data<AppState>, _req: HttpRequest) -> Result<HttpResponse, Error> {
let collection = data.storage.collection("questions").expect("collection questions");
let mut rng = rand::thread_rng();
let last_id = collection.last_id().unwrap();
let id = (1..(last_id + 1)).choose(&mut rng).unwrap();
let last_id = collection.last_id().expect("questions last id");
let id = (1..=last_id).choose(&mut rng).expect("random id");
let url = req.url_for("question", &[format!("{}", id)])?;
let url = format!("/q/{}", id);
Ok(HttpResponse::Found()
Ok(HttpResponse::TemporaryRedirect()
.header(header::LOCATION, url.as_str())
.finish())
}
@ -196,9 +179,9 @@ fn main() {
"read_only": true,
"no_lock": true,
}))
.unwrap();
.expect("options json parse");
let storage = Storage::new("db", options).unwrap();
let storage = Storage::new("db", options).expect("db open");
HttpServer::new(move || {
let data = AppState {
@ -208,19 +191,20 @@ fn main() {
App::new()
.wrap(Logger::default())
.data(data)
.service(actix_files::Files::new("/static", "./static"))
.route("/q", web::to(index))
.service(
web::scope("/q")
.service(actix_files::Files::new("/static", "./static"))
.service(
web::resource("/{id}")
.name("question") // <- set resource name, then it could be used in `url_for`
.name("question")
.guard(guard::Get())
.to(show_question),
)
.service(
web::resource("/{id}/a/")
.name("answer") // <- set resource name, then it could be used in `url_for`
.name("answer")
.guard(guard::Get())
.to(show_answer),
)
@ -228,8 +212,8 @@ fn main() {
)
.route("/", web::to(index))
})
.bind("127.0.0.1:8088")
.unwrap()
.bind("0.0.0.0:8088")
.expect("HttpServer::bind to 8088")
.run()
.unwrap();
.expect("HttpServer::run");
}

View File

@ -2,6 +2,7 @@
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="/q/static/style.css" />
<title>{% block title %}{% endblock title %}</title>
@ -9,5 +10,6 @@
<body>
{% include "nav.html" %}
<div id="content" class="container">{% block content %}{% endblock content %}</div>
<!-- Yandex.Metrika counter --> <script type="text/javascript" > (function (d, w, c) { (w[c] = w[c] || []).push(function() { try { w.yaCounter48214757 = new Ya.Metrika2({ id:48214757, clickmap:true, trackLinks:true, accurateTrackBounce:true, trackHash:true, ut:"noindex" }); } catch(e) { } }); var n = d.getElementsByTagName("script")[0], s = d.createElement("script"), f = function () { n.parentNode.insertBefore(s, n); }; s.type = "text/javascript"; s.async = true; s.src = "https://mc.yandex.ru/metrika/tag.js"; if (w.opera == "[object Opera]") { d.addEventListener("DOMContentLoaded", f, false); } else { f(); } })(document, window, "yandex_metrika_callbacks2"); </script> <noscript><div><img src="https://mc.yandex.ru/watch/48214757?ut=noindex" style="position:absolute; left:-9999px;" alt="" /></div></noscript> <!-- /Yandex.Metrika counter -->
</body>
</html>