Hi, first time poster here so apologies for bad code; trying to learn Rust. I'm a somewhat competent Go-programmer, which might explain me trying to slam down Rust code in a wrong way
I'm attempting to make a simple web application: It has a REST api(via Rocket), connects to a database(MySQL running locally) and there's a single endpoint. That's it!
I want to access the database connection inside the controller, I just cannot figure out how with Rocket.
Heres's my current code, pretty stuck at the moment:
#![feature(decl_macro)]
#[macro_use] extern crate rocket;
#[macro_use] extern crate rocket_contrib;
use serde::Serialize;
use rocket_contrib::json::Json;
#[macro_use]
extern crate mysql;
use mysql as my;
use mysql::Pool;
use mysql::consts::ColumnType::MYSQL_TYPE_DATE;
use mysql::prelude::Queryable;
#[get("/orgs")]
fn get_orgs(conn: MyDb) -> Json<Vec<Org>> {
// I need to have the db connection here to pass it to get_all.
let o = match Org::get_all() {
Ok(o) => o,
Err(e) => panic!(e),
};
Json(o)
}
#[derive(Serialize)]
pub struct Org {
pub id: Option<i32>,
pub name: String,
}
fn main() {
let url = "mysql://root:mysql@(localhost:33061)/rustdb";
let pool = Pool::new(url)?;
let mut conn = pool.get_conn();
// I need to pass "conn" around, first to get_orgs, then to Org::get_all.
rocket::ignite()
.mount("/", routes![get_orgs])
.launch();
}
impl Org {
fn get_all(mut conn: mysql::Conn) -> Result<Vec<Org>, Err> {
let all_orgs = conn
.query_map(
"SELECT id, name from organization",
|(id, name)| {
Org { id, name }
},
)?;
return match all_orgs() {
Ok(all_orgs) => all_orgs,
Err(e) => e,
};
}
}
So, when using #[get("/orgs")]
it probably does a bunch of code generation(assumption on my side - again, I'm new!). Googling around, I found this: State - Rocket Programming Guide - which looks correct. I just cannot for the life of me figure out a working example to connect to my local mysql instance. I'm sure I am missing something very simple here -- so keen to learn from you people! I am learning Rust to benchmark it with some of my own services -- if it performs well, perhaps I have a good argument to switch
Here are my dependencies:
[dependencies]
rocket = "0.4.2"
rocket_codegen = "0.4.2"
rocket_contrib = "0.4.2"
serde = {version = "1.0", features = ["derive"]}
serde_json = {version = "1.0"}
mysql = "*"
Once again, I'm just learning Rust so any critique to the code itself I wrote rather than the domain problem is also welcome!