Skip to content

Instantly share code, notes, and snippets.

@eonezhang
Forked from nicolov/Cargo.toml
Created October 20, 2018 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eonezhang/af1d28c22461ca5ab50603b10c424bf6 to your computer and use it in GitHub Desktop.
Save eonezhang/af1d28c22461ca5ab50603b10c424bf6 to your computer and use it in GitHub Desktop.
Rust API with Mysql
[package]
name = "api_example"
version = "0.1.0"
authors = ["nicolov"]
[dependencies]
iron = "*"
router = "*"
mysql = "*"
r2d2 = "*"
persistent = "0.0.6"
rustc-serialize = "0.3"
r2d2_mysql="0.2.2"
extern crate iron;
extern crate router;
extern crate mysql;
extern crate r2d2_mysql;
extern crate r2d2;
extern crate persistent;
extern crate rustc_serialize;
use iron::prelude::*;
use iron::typemap::Key;
use iron::status;
use router::{Router};
use std::default::Default;
use mysql::value::from_row;
use rustc_serialize::json;
use persistent::Read;
// struct for `visits` table in the database
#[derive(Debug, PartialEq, Eq, RustcEncodable)]
struct Visit {
id: i32,
region: String,
}
#[derive(Copy, Clone)]
pub struct DbPool;
impl iron::typemap::Key for DbPool {
type Value = r2d2::Pool<r2d2_mysql::MysqlConnectionManager>;
}
// GET endpoint
fn visit_list_handler (req: &mut Request) -> IronResult<Response> {
// get the db pool from iron-persistent
let db_pool = &req.get::<Read<DbPool>>().unwrap();
// get a connection from the pool
let mut conn = db_pool.get().unwrap();
let latest: Vec<Visit> =
conn.prep_exec("SELECT id, region FROM visits ORDER BY date desc LIMIT 10", ())
.map(|res| {
res.map(|x| x.unwrap())
.map(|row| {
let (id, region) = from_row(row);
Visit {
id: id,
region: region,
}
}).collect()
}).unwrap();
Ok(Response::with((status::Ok,
json::encode(&latest).unwrap())))
}
fn main() {
/*
* iron-router configuration with a couple of routes
*/
let mut router = Router::new();
// handler for GET requests
router.get(r"visit_list", visit_list_handler);
let mut chain = iron::Chain::new(router);
/*
* Database pool (r2d2) configuration
*/
let db_url = "mysql://user:pwd@localhost/rust_test_db";
let config = r2d2::Config::default();
let manager = r2d2_mysql::MysqlConnectionManager::new(db_url).unwrap();
/*
* enable the iron-persistent middleware to pass the DB pool
* to individual request threads
*/
chain.link(persistent::Read::<DbPool>::both(
r2d2::Pool::new(config, manager).unwrap()));
println!("Running server on port 3000");
Iron::new(chain).http("localhost:3000").unwrap();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment