From f9051a919fa9af44a5703f55afc11e91607d68c6 Mon Sep 17 00:00:00 2001 From: Akshay Date: Sun, 23 Aug 2020 22:17:50 +0530 Subject: attempt to use single db connection --- src/main.rs | 11 +++++++++-- src/service.rs | 50 +++++++++++++++++++++++++++----------------------- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/src/main.rs b/src/main.rs index 6b48957..c9819d0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,15 +4,22 @@ use hyper::Server; use log::trace; mod db; +use db::init_db; mod service; use service::shortner_service; +use std::sync::{Arc, Mutex}; + fn main() -> Result<()> { pretty_env_logger::init(); smol::run(async { let addr = ([127, 0, 0, 1], 3000).into(); - let service = - make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(shortner_service)) }); + let service = make_service_fn(move |_| async { + Ok::<_, hyper::Error>(service_fn(move |req| { + let db_conn = init_db("./urls.db_3").unwrap(); + shortner_service(req, db_conn) + })) + }); let server = Server::bind(&addr).serve(service); trace!("Listening on http://{}", addr); server.await.unwrap(); diff --git a/src/service.rs b/src/service.rs index 5883b40..41aa048 100644 --- a/src/service.rs +++ b/src/service.rs @@ -1,15 +1,14 @@ use anyhow::{Context, Result}; use hyper::header::CONTENT_TYPE; use hyper::{Body, Method, Request, Response, StatusCode}; -use log::{debug, error, info, trace}; +use log::{error, info, trace}; use multer::Multipart; use nanoid::nanoid; use rusqlite::{params, Connection}; use url::form_urlencoded; use std::collections::HashMap; - -use crate::db::init_db; +use std::sync::{Arc, Mutex}; fn respond_with_shortlink>(shortlink: S) -> Response { info!("Successfully generated shortlink"); @@ -39,7 +38,7 @@ fn shorten>(url: S, conn: &mut Connection) -> Result { } } -fn get_link>(url: S, conn: &mut Connection) -> Result> { +fn get_link>(url: S, conn: &Connection) -> Result> { let url = url.as_ref(); let mut stmt = conn.prepare("select * from urls where shortlink = ?1")?; let mut rows = stmt.query(params![url.to_string()])?; @@ -72,9 +71,29 @@ async fn process_multipart( Ok(respond_with_status(StatusCode::UNPROCESSABLE_ENTITY)) } -pub async fn shortner_service(req: Request) -> Result> { - let mut conn = init_db("./urls.db_3").unwrap(); +async fn process_form(req: Request, conn: &mut Connection) -> Result> { + let b = hyper::body::to_bytes(req) + .await + .with_context(|| format!("Failed to stream request body!"))?; + + let params = form_urlencoded::parse(b.as_ref()) + .into_owned() + .collect::>(); + if let Some(n) = params.get("shorten") { + trace!("POST: {}", &n); + let s = shorten(n, conn)?; + return Ok(respond_with_shortlink(s)); + } else { + error!("Invalid form"); + return Ok(respond_with_status(StatusCode::UNPROCESSABLE_ENTITY)); + } +} + +pub async fn shortner_service( + req: Request, + mut conn: Arc>, +) -> Result> { match req.method() { &Method::POST => { let boundary = req @@ -84,22 +103,7 @@ pub async fn shortner_service(req: Request) -> Result> { .and_then(|ct| multer::parse_boundary(ct).ok()); if boundary.is_none() { - let b = hyper::body::to_bytes(req) - .await - .with_context(|| format!("Failed to stream request body!"))?; - - let params = form_urlencoded::parse(b.as_ref()) - .into_owned() - .collect::>(); - - if let Some(n) = params.get("shorten") { - trace!("POST: {}", &n); - let s = shorten(n, &mut conn)?; - return Ok(respond_with_shortlink(s)); - } else { - error!("Invalid form"); - return Ok(respond_with_status(StatusCode::UNPROCESSABLE_ENTITY)); - } + return process_form(req, &mut conn).await; } trace!("Attempting to parse multipart request"); @@ -108,7 +112,7 @@ pub async fn shortner_service(req: Request) -> Result> { &Method::GET => { trace!("GET: {}", req.uri()); let shortlink = req.uri().path().to_string(); - let link = get_link(&shortlink[1..], &mut conn); + let link = get_link(&shortlink[1..], &conn); if let Some(l) = link.unwrap() { trace!("Found in database, redirecting ..."); Ok(Response::builder() -- cgit v1.2.3