Struct Client

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

This struct represents a client which has connected to the µHTTP server.microhttp

If an instance of this struct is dropped, the connection is closed.

Implementations§

Source§

impl Client

Source

pub fn addr(&self) -> SocketAddr

Return the address of the requesting client, for example “1.2.3.4:9435”.

Examples found in repository?
examples/echo.rs (line 21)
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 request(&self) -> &Option<String>

Return the request the client made or None if the client didn’t make any or an invalid one.

Note: At the moment, only HTTP GET is supported. Any other requests will not be collected.

Examples found in repository?
examples/echo.rs (line 20)
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 respond_ok(&mut self, data: &[u8]) -> Result<usize>

Send a HTTP 200 OK response to the client + the provided data. The data may be an empty array, for example the following implementation echos all requests except “/hello”:

Consider using respond_ok_chunked for sending file-backed data.

use micro_http_server::MicroHTTP;
use std::io::*;
let server = MicroHTTP::new("127.0.0.1:4000").expect("Could not create server.");
let mut client = server.next_client().unwrap().unwrap();
let request_str: String = client.request().as_ref().unwrap().clone();

match request_str.as_ref() {
	"/hello" => client.respond_ok(&[]),
    _ => client.respond_ok(request_str.as_bytes())  // Echo request
};
Examples found in repository?
examples/echo.rs (line 22)
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 respond_ok_chunked( &mut self, data: impl Read, content_size: usize, ) -> Result<usize>

Send a HTTP 200 OK response to the client + the provided data. The data may be any type implementing Read and will be read in chunks. This is useful for serving file-backed data that should not be loaded into memory all at once.

use micro_http_server::MicroHTTP;
use std::io::*;
use std::fs::*;
let server = MicroHTTP::new("127.0.0.1:4000").expect("Could not create server.");
let mut client = server.next_client().unwrap().unwrap();
client.request();

let mut file_handle = OpenOptions::new()
	.read(true)
	.write(false)
	.open("/some/local/file")
	.unwrap();
let file_len = file_handle.metadata().unwrap().len() as usize;

client.respond_ok_chunked(file_handle, file_len);
Source

pub fn respond( &mut self, status_code: &str, data: &[u8], headers: &Vec<String>, ) -> Result<usize>

Send response data to the client.

This is similar to respond_ok, but you may control the details yourself.

Consider using respond_chunked for sending file-backed data.

§Parameters
  • status_code: Select the status code of the response, e.g. 200 OK.
  • data: Data to transmit. May be empty.
  • headers: Additional headers to add to the response. May be empty.

Calling respond("200 OK", data, &vec!()) is the same as calling respond_ok(data).

Source

pub fn respond_chunked( &mut self, status_code: &str, data: impl Read, content_size: usize, headers: &Vec<String>, ) -> Result<usize>

Send repsonse data to the client.

This is similar to respond_ok_chunked, but you may control the details yourself.

§Parameters
  • status_code: Select the status code of the response, e.ge 200 OK.
  • data: Data to transmit. May be empty
  • content_size: Size of the data to transmit in bytes
  • headers: Additional headers to add to the response. May be empty.

Calling respond_chunked("200 OK", data, content_size, &vec!()) is the same as calling repsond_ok_chunked(data, content_size).

Trait Implementations§

Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Client

§

impl RefUnwindSafe for Client

§

impl Send for Client

§

impl Sync for Client

§

impl Unpin for Client

§

impl UnwindSafe for Client

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.