Book Image

Mastering Rust

By : Vesa Kaihlavirta
Book Image

Mastering Rust

By: Vesa Kaihlavirta

Overview of this book

<p>If concurrent programs are giving you sleepless nights, Rust is your go-to language. Being one of the first ever comprehensive books on Rust, it is filled with real-world examples and explanations, showing you how you can build scalable and reliable programs for your organization.</p> <p>We’ll teach you intermediate to advanced level concepts that make Rust a great language. Improving performance, using generics, building macros, and working with threads are just some of the topics we’ll cover. We’ll talk about the official toolsets and ways to discover more. The book contains a mix of theory interspersed with hands-on tasks, so you acquire the skills as well as the knowledge. Since programming cannot be learned by just reading, we provide exercises (and solutions) to hammer the concepts in.</p> <p>After reading this book, you will be able to implement Rust for your enterprise project, deploy the software, and will know the best practices of coding in Rust.</p>
Table of Contents (22 chapters)
Title Page
Credits
About the Author
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface

Hyper as a server


Let's go to the other aspect of Hyper: serving HTTP content. The basic usage is simple: you define a listening address and attach a handler to it. Since it may be called from several threads by Hyper, the handler that it needs to implement the Sync trait. Hyper provides a simple implementation for functions and closures, which takes a parameter for the Request and a Response. So, a simple logging HTTP server could look like this:

extern crate hyper; 
extern crate chrono; 

use hyper::server::{Server, Request, Response}; 
use hyper::header::UserAgent; 
use hyper::status::StatusCode; 
use chrono::*; 

fn log_request(req: Request, mut res: Response) { 
    let date = UTC::now(); 
    let user_agent = req.headers.get::<UserAgent>().unwrap(); 
    let mut status = res.status_mut(); 
    *status = StatusCode::Ok; 

    println!("{} {} \"{} {} {}\" {} \"{}\"", 
             req.remote_addr, 

             date, 
             req.method, 
             req.uri, 
          ...