読者です 読者をやめる 読者になる 読者になる

万年素人からHackerへの道

万年素人がHackerになれるまで殴り書きするぜ。

NickelとrustとPostgreSQL連携メモテンプレ

AdventCalendar2015 - nickel Webフレームワークを使ってみる - Qiita

ここでの参照。

DB作成はしている前提

#[macro_use] extern crate nickel;

extern crate r2d2;
extern crate postgres;
extern crate openssl;
extern crate nickel_postgres;
extern crate r2d2_postgres;

use nickel::{Nickel,HttpRouter};
use r2d2::NopErrorHandler;
use nickel_postgres::{PostgresMiddleware, PostgresRequestExtensions};
use r2d2_postgres::{SslMode, PostgresConnectionManager};

fn main() {
    let mut serv = Nickel::new();
    let config = r2d2::Config::default();
    let manager = PostgresConnectionManager::new("postgres://postgres@localhost",
                                                 SslMode::None).unwrap();
    let dbpool = r2d2::Pool::new(config, manager).unwrap();

    serv.get("/count",
             middleware! {|req, res|

             let pool = dbpool.clone();
             let conn = pool.get().unwrap();

             let stmt = conn.prepare("SELECT counter FROM counter WHERE id = 0").unwrap();
             let rows = &stmt.query(&[]).unwrap();
             let mut counter:i16 = 0; // Int2(smallint) of Postgres is i16
             for row in rows {
                 counter = row.get(0);
             }

             // also print to stdout
             println!("counter value is {}", counter);

             // Up and save the counter value (+1)
             conn.execute("UPDATE counter SET counter = counter + 1 WHERE id = 0", &[]).unwrap();

             format!("<h1>Hello</h1><br>your are the visitor # {}.\n", counter)
             });
    serv.listen("localhost:6767");
}
[package]
name = "nickel-helloworld"
version = "0.1.0"
authors = ["shinriyo"]

[dependencies]
nickel = "*"
r2d2 = "*"
#postgres = "*"
postgres = "0.11"
openssl = "*"
r2d2_postgres = "*"

[dependencies.nickel_postgres]
git = "https://github.com/nickel-org/nickel-postgres.git"