Struct MicroHTTP

Source
pub struct MicroHTTP { /* private fields */ }
Expand description

This is the main struct of the µHTTP server.

Implementations§

Source§

impl MicroHTTP

Source

pub fn new(interface: impl ToSocketAddrs) -> Result<MicroHTTP, Error>

Create a new MicroHTTP server on the given interface.microhttp

Internally, this just tries to create a TcpListener - nothing special. Returns the new MicroHTTP server or an std::io::Error on error.

§Example
use micro_http_server::MicroHTTP;

let interface: &str = "127.0.0.1:3000";
let server = MicroHTTP::new(interface)
    .expect("Could not create server, maybe the port is already being used?");
Examples found in repository?
examples/echo.rs (line 5)
4pub fn main() {
5	let server = MicroHTTP::new("127.0.0.1:3000")
6		.expect("Could not create server.");
7
8	println!("Waiting for requests on: http://127.0.0.1:3000");
9
10	loop {
11		let result = server.next_client();
12		if result.is_err() {
13			println!("Server failed: {:?}", result);
14			break;
15		}
16
17		match result.unwrap() {
18			None => ::std::thread::sleep(::std::time::Duration::from_millis(500)),
19			Some(mut client) => {
20				if client.request().is_none() {
21					println!("Client {} didn't send any request", client.addr());
22					client.respond_ok("No request :(".as_bytes())
23						.expect("Could not send data to client!");
24				} else {
25					let request_copy = client.request().as_ref().unwrap().clone();
26
27					println!("Client {} requested {}, echoing...", client.addr(), request_copy);
28					client.respond_ok(request_copy.as_bytes())
29						.expect("Could not send data to client!");
30				}
31			}
32		}
33	}
34}
Source

pub fn set_nonblocking(&mut self, state: bool) -> Result<(), Error>

Set whether or not the underlying TcpListener awaits connections in nonblocking mode

Source

pub fn next_client(&self) -> Result<Option<Client>, Error>

Return the next available client which is incoming at this server.

Returns either:

  • Some(client) if a client is available
  • None if no client is currently available (i.e. no one has reached out to the server yet)
  • std::io::Error if something is wrong with the server.
§Example
use std::{io::{Read,Write},net::TcpStream};
use micro_http_server::MicroHTTP;

let server = MicroHTTP::new("127.0.0.1:3000").expect("Could not create server.");
println!("[Server] Waiting for a client @ 127.0.0.1:3000...");

loop {
    let result = server.next_client();
    if result.is_err() {
        println!("Something is wrong with the client: {:?}", result.unwrap_err());
        break;
    }

    match result.unwrap() {
        None => {
            // Here you can sleep or do something else.
            println!("Still waiting for clients...");
        },
        Some(client) => {
            println!("Got a new client from: {:?}", client.addr());
        }
    }
}
Examples found in repository?
examples/echo.rs (line 11)
4pub fn main() {
5	let server = MicroHTTP::new("127.0.0.1:3000")
6		.expect("Could not create server.");
7
8	println!("Waiting for requests on: http://127.0.0.1:3000");
9
10	loop {
11		let result = server.next_client();
12		if result.is_err() {
13			println!("Server failed: {:?}", result);
14			break;
15		}
16
17		match result.unwrap() {
18			None => ::std::thread::sleep(::std::time::Duration::from_millis(500)),
19			Some(mut client) => {
20				if client.request().is_none() {
21					println!("Client {} didn't send any request", client.addr());
22					client.respond_ok("No request :(".as_bytes())
23						.expect("Could not send data to client!");
24				} else {
25					let request_copy = client.request().as_ref().unwrap().clone();
26
27					println!("Client {} requested {}, echoing...", client.addr(), request_copy);
28					client.respond_ok(request_copy.as_bytes())
29						.expect("Could not send data to client!");
30				}
31			}
32		}
33	}
34}

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.