万年素人からHackerへの道

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

  • ・資産運用おすすめ
    10万円は1000円くらい利益
    • ・寄付お願いします
      YENTEN:YYzNPzdsZWqr5THWAdMrKDj7GT8ietDc2W
      BitZenny:ZfpUbVya8MWQkjjGJMjA7P9pPkqaLnwPWH
      c0ban:8KG95GXdEquNpPW8xJAJf7nn5kbimQ5wj1

    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"