Skip to content

Instantly share code, notes, and snippets.

@jakecraige
Created August 5, 2017 21:21
Show Gist options
  • Save jakecraige/f15026bc33d920d592578fafbb67a93d to your computer and use it in GitHub Desktop.
Save jakecraige/f15026bc33d920d592578fafbb67a93d to your computer and use it in GitHub Desktop.
First Rust Web App
extern crate iron;
extern crate logger;
extern crate env_logger;
extern crate router;
extern crate bodyparser;
extern crate persistent;
extern crate serde_json;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate diesel;
extern crate dotenv;
#[macro_use] extern crate diesel_codegen;
use iron::prelude::*;
use iron::status;
use logger::Logger;
use router::Router;
use persistent::Read;
use diesel::prelude::*;
use diesel::pg::PgConnection;
use dotenv::dotenv;
use std::env;
infer_schema!("dotenv:DATABASE_URL");
const MAX_BODY_LENGTH: usize = 1024 * 1024 * 10;
#[derive(Debug, Clone, Deserialize, Serialize, Queryable)]
struct User {
id: i32,
name: String,
password: String,
}
#[derive(Insertable, Debug, Clone, Deserialize, Serialize)]
#[table_name="users"]
struct NewUser<'a> {
name: &'a str,
password: &'a str,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
struct ReqUser {
name: String,
password: String,
}
fn establish_connection() -> PgConnection {
dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
PgConnection::establish(&database_url)
.expect(&format!("Error connecting to {}", database_url))
}
fn main() {
let _ = env_logger::init();
let router = build_router();
let (logger_before, logger_after) = Logger::new(None);
let mut chain = Chain::new(router);
chain.link_before(logger_before);
chain.link_before(Read::<bodyparser::MaxBodyLength>::one(MAX_BODY_LENGTH));
chain.link_after(logger_after);
Iron::new(chain).http("localhost:3000").unwrap();
}
fn build_router() -> Router {
let mut router = Router::new();
router.get("/users", get_users, "users");
router.post("/users", create_user, "create_user");
return router
}
fn get_users(_: &mut Request) -> IronResult<Response> {
use users::dsl::*;
let conn = establish_connection();
let results = users.load::<User>(&conn).expect("error loading users");
let json = serde_json::to_string(&results).unwrap();
Ok(Response::with((status::Ok, json)))
}
fn create_user(req: &mut Request) -> IronResult<Response> {
use users;
let conn = establish_connection();
let user = req.get::<bodyparser::Struct<ReqUser>>();
match user {
Ok(Some(user)) => {
let new_user = NewUser { name: &user.name, password: &user.password };
let user: User = diesel::insert(&new_user).into(users::table).get_result(&conn).expect("error saving new user");
let json_user = serde_json::to_string(&user).unwrap();
Ok(Response::with((status::Ok, json_user)))
},
Ok(None) => Ok(Response::with((status::UnprocessableEntity, "Must provide a user"))),
Err(_err) => Ok(Response::with((status::UnprocessableEntity, "Invalid json")))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment