· 5 years ago · Feb 03, 2020, 03:56 AM
1#![feature(proc_macro_hygiene, decl_macro)]
2
3#[macro_use]
4extern crate rocket;
5#[macro_use]
6extern crate rocket_contrib;
7#[macro_use]
8extern crate serde_derive;
9
10use postgres::{Connection, TlsMode};
11use rocket_contrib::databases::postgres;
12use rocket_contrib::json::{Json, JsonValue};
13
14type ID = i64;
15
16#[database("postgres")]
17struct PostgresDbConn(postgres::Connection);
18
19#[derive(Serialize, Deserialize, Debug)]
20struct User {
21 id: i64,
22 blob: JsonValue,
23}
24
25#[get("/ping")]
26fn ping() -> &'static str {
27 "pong"
28}
29
30#[get("/user/<id>")]
31fn get_user(id: ID, db: PostgresDbConn) -> Option<JsonValue> {
32 let result = db.query("SELECT blob FROM users WHERE id = $1", &[&id]);
33 match result {
34 Ok(row) => Some(row.get(0).get("blob")),
35 Err(_) => None,
36 }
37}
38
39fn main() {
40 let server = rocket::ignite();
41 let conf = server.config();
42 let pg_url = conf
43 .get_extra("databases")
44 .unwrap()
45 .get("postgres")
46 .unwrap()
47 .get("url")
48 .unwrap()
49 .as_str()
50 .unwrap();
51 println!("{}", pg_url);
52
53 let conn = Connection::connect(pg_url, TlsMode::None).unwrap();
54 conn.execute(
55 "CREATE TABLE IF NOT EXISTS users (id BIGSERIAL PRIMARY KEY, blob JSONB NOT NULL);",
56 &[],
57 )
58 .unwrap();
59
60 server
61 .mount("/", routes![ping, get_user])
62 .attach(PostgresDbConn::fairing())
63 .launch();
64}