Skip to content

Instantly share code, notes, and snippets.

@marcusbuffett
Created September 2, 2020 22:38
Show Gist options
  • Save marcusbuffett/eaa105337719b249cba47b0522a70bc9 to your computer and use it in GitHub Desktop.
Save marcusbuffett/eaa105337719b249cba47b0522a70bc9 to your computer and use it in GitHub Desktop.
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use]
extern crate rocket;
extern crate anyhow;
extern crate sled;
use rocket_contrib::json::Json;
use serde::{Deserialize, Serialize};
use anyhow::anyhow;
use rocket::fairing::AdHoc;
use rocket::State;
use sled::Db;
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Book {
uuid: String,
}
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[get("/books/<uuid>")]
fn get_books(db: State<Db>, uuid: String) -> anyhow::Result<String> {
let book = db.get(uuid)?.ok_or(anyhow!("BLAH"))?;
let book: Book = bincode::deserialize(&book)?;
let book = serde_json::to_string(&book)?;
Ok(book)
}
#[post("/books", data = "<book>")]
fn patch_book(db: State<Db>, book: Json<Book>) -> anyhow::Result<&'static str> {
let encoded: Vec<u8> = bincode::serialize(&(*book))?;
db.insert(&book.uuid, encoded)?;
Ok("Blah")
}
fn main() {
let path = "./data/sled";
let db = sled::open(path).expect("Failed to open sled db");
let db_clone = db.clone();
rocket::ignite()
.manage(db)
.mount("/", routes![index, get_books, patch_book])
.launch();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment