Skip to content

Commit

Permalink
actix examples in actix release version
Browse files Browse the repository at this point in the history
  • Loading branch information
krircc committed Apr 13, 2018
1 parent ad58e55 commit 3ebde8e
Show file tree
Hide file tree
Showing 88 changed files with 3,829 additions and 2 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Generated by Cargo
# will have compiled files and executables
/target/
/*/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
/*/Cargo.lock

# These are backup files generated by rustfmt
**/*.rs.bk
10 changes: 10 additions & 0 deletions basics/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "basics"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]

[dependencies]
futures = "0.1"
env_logger = "0.5"
actix = "0.5"
actix-web = "^0.5"
20 changes: 20 additions & 0 deletions basics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# basics

## Usage

### server

```bash
cd actix-web/examples/basics
cargo run
# Started http server: 127.0.0.1:8080
```

### web client

- [http://localhost:8080/index.html](http://localhost:8080/index.html)
- [http://localhost:8080/async/bob](http://localhost:8080/async/bob)
- [http://localhost:8080/user/bob/](http://localhost:8080/user/bob/) plain/text download
- [http://localhost:8080/test](http://localhost:8080/test) (return status switch GET or POST or other)
- [http://localhost:8080/static/index.html](http://localhost:8080/static/index.html)
- [http://localhost:8080/static/notexit](http://localhost:8080/static/notexit) display 404 page
136 changes: 136 additions & 0 deletions basics/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
#![allow(unused_variables)]
#![cfg_attr(feature="cargo-clippy", allow(needless_pass_by_value))]

extern crate actix;
extern crate actix_web;
extern crate env_logger;
extern crate futures;
use futures::Stream;

use std::{io, env};
use actix_web::{error, fs, pred, server,
App, HttpRequest, HttpResponse, Result, Error};
use actix_web::http::{header, Method, StatusCode};
use actix_web::middleware::{self, RequestSession};
use futures::future::{FutureResult, result};

/// favicon handler
fn favicon(req: HttpRequest) -> Result<fs::NamedFile> {
Ok(fs::NamedFile::open("../static/favicon.ico")?)
}

/// simple index handler
fn index(mut req: HttpRequest) -> Result<HttpResponse> {
println!("{:?}", req);

// example of ...
if let Ok(ch) = req.poll() {
if let futures::Async::Ready(Some(d)) = ch {
println!("{}", String::from_utf8_lossy(d.as_ref()));
}
}

// session
let mut counter = 1;
if let Some(count) = req.session().get::<i32>("counter")? {
println!("SESSION value: {}", count);
counter = count + 1;
req.session().set("counter", counter)?;
} else {
req.session().set("counter", counter)?;
}


// response
Ok(HttpResponse::build(StatusCode::OK)
.content_type("text/html; charset=utf-8")
.body(include_str!("../static/welcome.html")))

}

/// 404 handler
fn p404(req: HttpRequest) -> Result<fs::NamedFile> {
Ok(fs::NamedFile::open("./static/404.html")?
.set_status_code(StatusCode::NOT_FOUND))
}


/// async handler
fn index_async(req: HttpRequest) -> FutureResult<HttpResponse, Error>
{
println!("{:?}", req);

result(Ok(HttpResponse::Ok()
.content_type("text/html")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))))
}

/// handler with path parameters like `/user/{name}/`
fn with_param(req: HttpRequest) -> HttpResponse
{
println!("{:?}", req);

HttpResponse::Ok()
.content_type("test/plain")
.body(format!("Hello {}!", req.match_info().get("name").unwrap()))
}

fn main() {
env::set_var("RUST_LOG", "actix_web=debug");
env::set_var("RUST_BACKTRACE", "1");
env_logger::init();
let sys = actix::System::new("basic-example");

let addr = server::new(
|| App::new()
// enable logger
.middleware(middleware::Logger::default())
// cookie session middleware
.middleware(middleware::SessionStorage::new(
middleware::CookieSessionBackend::signed(&[0; 32]).secure(false)
))
// register favicon
.resource("/favicon.ico", |r| r.f(favicon))
// register simple route, handle all methods
.resource("/index.html", |r| r.f(index))
// with path parameters
.resource("/user/{name}/", |r| r.method(Method::GET).f(with_param))
// async handler
.resource("/async/{name}", |r| r.method(Method::GET).a(index_async))
.resource("/test", |r| r.f(|req| {
match *req.method() {
Method::GET => HttpResponse::Ok(),
Method::POST => HttpResponse::MethodNotAllowed(),
_ => HttpResponse::NotFound(),
}
}))
.resource("/error.html", |r| r.f(|req| {
error::InternalError::new(
io::Error::new(io::ErrorKind::Other, "test"), StatusCode::OK)
}))
// static files
.handler("/static/", fs::StaticFiles::new("../static/"))
// redirect
.resource("/", |r| r.method(Method::GET).f(|req| {
println!("{:?}", req);
HttpResponse::Found()
.header(header::LOCATION, "/index.html")
.finish()
}))
// default
.default_resource(|r| {
// 404 for GET request
r.method(Method::GET).f(p404);

// all requests that are not `GET`
r.route().filter(pred::Not(pred::Get())).f(
|req| HttpResponse::MethodNotAllowed());
}))

.bind("127.0.0.1:8080").expect("Can not bind to 127.0.0.1:8080")
.shutdown_timeout(0) // <- Set shutdown timeout to 0 seconds (default 60s)
.start();

println!("Starting http server: 127.0.0.1:8080");
let _ = sys.run();
}
7 changes: 7 additions & 0 deletions basics/static/404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
<!DOCTYPE html><html><head><title>actix - basics</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" /></head>
<body>
<a href="index.html">back to home</a>
<h1>404</h1>
</body>
</html>
6 changes: 6 additions & 0 deletions basics/static/welcome.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<!DOCTYPE html><html><head><title>actix - basics</title>
<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" /></head>
<body>
<h1>Welcome <img width="30px" height="30px" src="/static/actixLogo.png" /></h1>
</body>
</html>
1 change: 1 addition & 0 deletions diesel/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DATABASE_URL=file:test.db
19 changes: 19 additions & 0 deletions diesel/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[package]
name = "diesel-example"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]

[dependencies]
env_logger = "0.5"
actix = "0.5"
actix-web = "^0.5"

futures = "0.1"
uuid = { version = "0.5", features = ["serde", "v4"] }
serde = "1.0"
serde_json = "1.0"
serde_derive = "1.0"

diesel = { version = "^1.1.0", features = ["sqlite", "r2d2"] }
r2d2 = "0.8"
dotenv = "0.10"
43 changes: 43 additions & 0 deletions diesel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# diesel

Diesel's `Getting Started` guide using SQLite for Actix web

## Usage

### init database sqlite

```bash
cargo install diesel_cli --no-default-features --features sqlite
cd actix-web/examples/diesel
echo "DATABASE_URL=file:test.db" > .env
diesel migration run
```

### server

```bash
# if ubuntu : sudo apt-get install libsqlite3-dev
# if fedora : sudo dnf install libsqlite3x-devel
cd actix-web/examples/diesel
cargo run (or ``cargo watch -x run``)
# Started http server: 127.0.0.1:8080
```

### web client

[http://127.0.0.1:8080/NAME](http://127.0.0.1:8080/NAME)

### sqlite client

```bash
# if ubuntu : sudo apt-get install sqlite3
# if fedora : sudo dnf install sqlite3x
sqlite3 test.db
sqlite> .tables
sqlite> select * from users;
```
## Postgresql
You will also find another complete example of diesel+postgresql on [https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix](https://github.com/TechEmpower/FrameworkBenchmarks/tree/master/frameworks/Rust/actix)
1 change: 1 addition & 0 deletions diesel/migrations/20170124012402_create_users/down.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE users
4 changes: 4 additions & 0 deletions diesel/migrations/20170124012402_create_users/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
CREATE TABLE users (
id VARCHAR NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL
)
55 changes: 55 additions & 0 deletions diesel/src/db.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
//! Db executor actor
use uuid;
use diesel;
use actix_web::*;
use actix::prelude::*;
use diesel::prelude::*;
use diesel::r2d2::{Pool, ConnectionManager};

use models;
use schema;

/// This is db executor actor. We are going to run 3 of them in parallel.
pub struct DbExecutor(pub Pool<ConnectionManager<SqliteConnection>>);

/// This is only message that this actor can handle, but it is easy to extend number of
/// messages.
pub struct CreateUser {
pub name: String,
}

impl Message for CreateUser {
type Result = Result<models::User, Error>;
}

impl Actor for DbExecutor {
type Context = SyncContext<Self>;
}

impl Handler<CreateUser> for DbExecutor {
type Result = Result<models::User, Error>;

fn handle(&mut self, msg: CreateUser, _: &mut Self::Context) -> Self::Result {
use self::schema::users::dsl::*;

let uuid = format!("{}", uuid::Uuid::new_v4());
let new_user = models::NewUser {
id: &uuid,
name: &msg.name,
};

let conn: &SqliteConnection = &self.0.get().unwrap();

diesel::insert_into(users)
.values(&new_user)
.execute(conn)
.expect("Error inserting person");

let mut items = users
.filter(id.eq(&uuid))
.load::<models::User>(conn)
.expect("Error loading person");

Ok(items.pop().unwrap())
}
}
Loading

0 comments on commit 3ebde8e

Please sign in to comment.