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
impl Client
Sourcepub fn addr(&self) -> SocketAddr
pub fn addr(&self) -> SocketAddr
Return the address of the requesting client, for example “1.2.3.4:9435”.
Examples found in repository?
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}
Sourcepub fn request(&self) -> &Option<String>
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?
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}
Sourcepub fn respond_ok(&mut self, data: &[u8]) -> Result<usize>
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?
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}
Sourcepub fn respond_ok_chunked(
&mut self,
data: impl Read,
content_size: usize,
) -> Result<usize>
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);
Sourcepub fn respond(
&mut self,
status_code: &str,
data: &[u8],
headers: &Vec<String>,
) -> Result<usize>
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)
.
Sourcepub fn respond_chunked(
&mut self,
status_code: &str,
data: impl Read,
content_size: usize,
headers: &Vec<String>,
) -> Result<usize>
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.ge200 OK
.data
: Data to transmit. May be emptycontent_size
: Size of the data to transmit in bytesheaders
: 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)
.