rocket with db connection and thiserror

This commit is contained in:
Viv Lim 2021-10-08 21:39:06 -07:00
commit fa243569cb
4 changed files with 1672 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
/target
/db

1600
Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

11
Cargo.toml Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "crab-forum"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
sled = "0.34"
rocket = "0.5.0-rc.1"
thiserror = "1.0.30"

59
src/main.rs Normal file
View File

@ -0,0 +1,59 @@
use std::{default::{self }, io::Cursor};
use rocket::{Request, Response, State, http::{ContentType, Status}, response};
use sled::{Db, IVec};
use thiserror::Error;
use rocket::response::Responder;
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[get("/append")]
fn append(db: &State<Db>) -> Result<String, AppendFailures> {
const key: &str = "test_nums";
let value = db.generate_id().unwrap();
let mut result: Vec<u8> = match db.get(key)? {
Some(r) => r.to_vec(),
None => Default::default()
};
result.push(69);
let response = format!("it's {:?}", result);
db.insert(key, result)?;
return Ok(response)
}
#[derive(Error, Debug)]
enum AppendFailures {
#[error("db error {0}")]
DbError(#[from] sled::Error)
}
impl<'r> Responder<'r, 'static> for AppendFailures {
fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
let error_msg: String = format!("Error: {:?}", self).into();
Response::build()
.header(ContentType::Plain)
.sized_body(error_msg.len(), Cursor::new(error_msg))
.status(Status {
code: 500,
})
.ok()
}
}
#[launch]
fn rocket() -> _ {
rocket::build()
.manage(sled::open("db").unwrap())
.mount("/", routes![index, append])
}