Crate tiny_http[][src]

Expand description

Simple usage

Creating the server

The easiest way to create a server is to call Server::http().

The http() function returns an IoResult<Server> which will return an error in the case where the server creation fails (for example if the listening port is already occupied).

let server = tiny_http::Server::http("0.0.0.0:0").unwrap();

A newly-created Server will immediatly start listening for incoming connections and HTTP requests.

Receiving requests

Calling server.recv() will block until the next request is available. This function returns an IoResult<Request>, so you need to handle the possible errors.


loop {
    // blocks until the next request is received
    let request = match server.recv() {
        Ok(rq) => rq,
        Err(e) => { println!("error: {}", e); break }
    };

    // do something with the request
    // ...
}

In a real-case scenario, you will probably want to spawn multiple worker tasks and call server.recv() on all of them. Like this:

let server = Arc::new(server);
let mut guards = Vec::with_capacity(4);

for _ in (0 .. 4) {
    let server = server.clone();

    let guard = thread::spawn(move || {
        loop {
            let rq = server.recv().unwrap();

            // ...
        }
    });

    guards.push(guard);
}

If you don’t want to block, you can call server.try_recv() instead.

Handling requests

The Request object returned by server.recv() contains informations about the client’s request. The most useful methods are probably request.method() and request.url() which return the requested method (GET, POST, etc.) and url.

To handle a request, you need to create a Response object. See the docs of this object for more infos. Here is an example of creating a Response from a file:

let response = tiny_http::Response::from_file(File::open(&Path::new("image.png")).unwrap());

All that remains to do is call request.respond():

let _ = request.respond(response);

Structs

HTTPVersion

HTTP version (usually 1.0 or 1.1).

Header

Represents a HTTP header.

HeaderField

Field of a header (eg. Content-Type, Content-Length, etc.)

IncomingRequests
Request

Represents an HTTP request made by a client.

Response

Object representing an HTTP response whose purpose is to be given to a Request.

Server

The main class of this library.

ServerConfig

Represents the parameters required to create a server.

SslConfig

Configuration of the server for SSL.

StatusCode

Status code of a request or response.

Enums

Method

HTTP request methods

Traits

ReadWrite

Dummy trait that regroups the Read and Write traits.

Type Definitions

ResponseBox

A Response without a template parameter.