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 immediately 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§
- HTTP
Version - HTTP version (usually 1.0 or 1.1).
- Header
- Represents a HTTP header.
- Header
Field - Field of a header (eg.
Content-Type,Content-Length, etc.) - Incoming
Requests - 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.
- Server
Config - Represents the parameters required to create a server.
- SslConfig
- Configuration of the server for SSL.
- Status
Code - Status code of a request or response.
- Test
Request - A simpler version of
Requestthat is useful for testing. No data actually goes anywhere.
Enums§
- Config
Listen Addr - Listen
Addr - Unified listen socket address. Either a
SocketAddrorstd::os::unix::net::SocketAddr. - Listener
- Unified listener. Either a
TcpListenerorstd::os::unix::net::UnixListener - Method
- HTTP request methods
Traits§
- Read
Write - Dummy trait that regroups the
ReadandWritetraits.
Type Aliases§
- Response
Box - A
Responsewithout a template parameter.