Skip to content

Instantly share code, notes, and snippets.

@Tristramg
Last active December 3, 2018 09:33
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 Tristramg/5862743abf397757aeee42655276600b to your computer and use it in GitHub Desktop.
Save Tristramg/5862743abf397757aeee42655276600b to your computer and use it in GitHub Desktop.
extern crate actix;
use actix::{Actor, Addr, Context, Handler, Message};
use std::time::Duration;
extern crate futures;
use actix::AsyncContext;
use futures::Future;
extern crate actix_web;
use actix_web::{http, server, App, AsyncResponder, Error, State};
struct MyActor {
ticker: i64,
pings: i64,
}
struct Ping;
impl Message for Ping {
type Result = Result<bool, std::io::Error>;
}
impl Handler<Ping> for MyActor {
type Result = Result<bool, std::io::Error>;
fn handle(&mut self, _msg: Ping, _ctx: &mut Context<Self>) -> Self::Result {
println!("Ping received");
self.pings += 1;
Ok(true)
}
}
impl Actor for MyActor {
type Context = Context<Self>;
fn started(&mut self, ctx: &mut Self::Context) {
ctx.run_interval(Duration::new(2, 0), |act, _ctx| {
act.ticker += 1;
println!("I ticked {} times and got {} pings", act.ticker, act.pings);
});
}
}
fn index(actor_addr: State<Addr<MyActor>>) -> Box<Future<Item = String, Error = Error>> {
actor_addr
.send(Ping)
.and_then(|_| Ok("pring sent!".to_owned()))
.map_err(Error::from)
.responder()
}
fn main() {
let system = actix::System::new("test");
let addr = MyActor {
ticker: 0,
pings: 0,
}.start();
server::new(move || {
App::with_state(addr.clone()).resource("/", |r| r.method(http::Method::GET).with(index))
}).bind("127.0.0.1:8088")
.unwrap()
.run();
system.run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment