This is a super simple HTTP server that doesn't get in the way.
It doesn't do much, but it doesn't hide much. Additional features are exposed through various modules, including:
This library is async, but does not dictate whether you use tokio, async-std, or something else.
My goal is to write a HTTP library that isn't confusing, doesn't prevent anything (even if it may require a few extra lines to get my goal), and has reasonable performance.
If you're up for it, look at [examples/simpleserver.rs], [examples/websocketserver.rs], and [examples/echo_server.rs]. They'll be up-to-date, unlike this doc.
Add to Cargo.toml
oc_http = "0.1.0"
I use async-std because it's easy, plus logging stuff;
async-std = {version = "1.8.0", features = ["attributes"]}
log = "0.4"
env_logger = "0.8"
Create a server:
``` use std::error::Error; use log::warn; use envlogger::Env; use asyncstd::{ task, io::{ BufReader, BufWriter, }, net::TcpListener, }; use futures::{ prelude::*, AsyncRead, AsyncWrite, };
async fn main() -> Result<(), Box
async fn handlerequest(stream: S)
where S: AsyncRead + AsyncWrite + Clone + Unpin
{
// parse the http request; prefer using BufWriter/BufReader for performance.
let mut reader = BufReader::new(stream.clone());
let mut writer = BufWriter::new(stream);
// Read the request
match ochttp::http(&mut reader).await {
Ok(req) => req,
Err(err) => {
warn!("Error {}", err);
return;
},
};
ochttp::respond(&mut writer, ochttp::Response{
code: 200,
reason: "OK",
headers: vec!(),
}).await.unwrap();
// after sending the HTTP header, we can write anything to the body
writer.write(b"