Quantcast
Viewing all articles
Browse latest Browse all 22

Deploying Rust applications to Heroku, with example code for Iron

Now with support for Iron, Cargo and Cargo.lock!

You can deploy an example Rust application to Heroku using this button:

Image may be NSFW.
Clik here to view.
Deploy

If you'd prefer to use the command line, you'll need git and the Heroku toolbelt. Once these are installed, run:

git clone https://github.com/emk/heroku-rust-cargo-hello.git
cd heroku-rust-cargo-hello
heroku create --buildpack https://github.com/emk/heroku-buildpack-rust.git
git push heroku master

This will download the example application, create a new Heroku project, and deploy the code to Heroku. That's it!

How it works

Our server is based on the Iron middleware library. We parse URL parameters and dispatch HTTP requests to the appropriate handler routine using Iron's router module:

fnmain(){letmutrouter=Router::new();router.get("/",hello);router.get("/:name",hello_name);Iron::new(router).listen(Ipv4Addr(0,0,0,0),get_server_port());}

The hello function returns an HTTP status code and the content to send to the user:

fnhello(_:&mutRequest)->IronResult<Response>{Ok(Response::with(status::Ok,"Hello world!"))}

The hello_name function is similar, but we look up the value of the :name parameter that we declared to the router, above.

fnhello_name(req:&mutRequest)->IronResult<Response>{letparams=req.extensions.find::<Router,Params>().unwrap();letname=params.find("name").unwrap();Ok(Response::with(status::Ok,format!("Hello, {}!",name)))}

The final piece needed to run on Heroku is a function to look up up our port number:

fnget_server_port()->Port{getenv("PORT").and_then(|s|from_str::<Port>(s.as_slice())).unwrap_or(8080)}

The full source code is available on GitHub. To learn more about Rust, see the excellent Rust guide.

Keep reading for notes on building the program locally and on configuring your own programs to run on Heroku.

Read more…


Viewing all articles
Browse latest Browse all 22

Trending Articles