Struct solicit::server::SimpleServer [] [src]

pub struct SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response {
    // some fields omitted
}

The struct implements a simple HTTP/2 server that allows users to register a request handler (a callback taking a ServerRequest and returning a Response) which is run on all received requests.

The handle_next method needs to be called regularly in order to have the server process received frames, as well as send out the responses.

This is an exceedingly simple implementation of an HTTP/2 server and is mostly an example of how the solicit::http API can be used to make one.

Examples

extern crate solicit;
use std::str;
use std::net::{TcpListener, TcpStream};
use std::thread;

use solicit::server::SimpleServer;

use solicit::http::Response;

fn main() {
    fn handle_client(stream: TcpStream) {
        let mut server = SimpleServer::new(stream, |req| {
            println!("Received request:");
            for header in req.headers.iter() {
                println!("  {}: {}",
                str::from_utf8(&header.0).unwrap(),
                str::from_utf8(&header.1).unwrap());
            }
            println!("Body:\n{}", str::from_utf8(&req.body).unwrap());

            // Return a dummy response for every request
            Response {
                headers: vec![
                    (b":status".to_vec(), b"200".to_vec()),
                    (b"x-solicit".to_vec(), b"Hello, World!".to_vec()),
                ],
                body: vec![65],
                stream_id: req.stream_id,
           }
        }).unwrap();
        while let Ok(_) = server.handle_next() {}
        println!("Server done (client disconnected)");
    }

    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();
    for stream in listener.incoming() {
        let stream = stream.unwrap();
        thread::spawn(move || {
            handle_client(stream)
        });
    }
}

Methods

impl<TS, H> SimpleServer<TS, H> where TS: TransportStream, H: FnMut(ServerRequest) -> Response
[src]

Creates a new SimpleServer that will use the given TransportStream to communicate to the client. Assumes that the stream is fully uninitialized -- no preface sent or read yet.

Handles the next incoming frame, blocking to receive it if nothing is available on the underlying stream.

Handling the frame can trigger the handler callback. Any responses returned by the handler are immediately flushed out to the client (blocking the call until it's done).