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
Content-Type
, Content-Length
, etc.)Request
.Request
that is useful for testing. No data actually goes anywhere.Enums
SocketAddr
or std::os::unix::net::SocketAddr
.TcpListener
or std::os::unix::net::UnixListener
Traits
Read
and Write
traits.Type Definitions
Response
without a template parameter.