To create an HTTP server in Rust, we need to use the hyper
crate. Here's an example code for a simple HTTP server that runs on localhost:8080
and reads the request body:
main.rs1783 chars51 lines
In the handle_request
function, we first check if the request method is POST
. If it is, we get the content_type
from the request headers (defaulting to "text/plain"
if not found), and then read the request body using req.into_body().concat2()
. The concat2
function returns a Future
that resolves to a Chunk
, which we can convert to a String
using String::from_utf8_lossy
. Finally, we return a Response
with a status of 200
, a body containing a greeting that includes the content_type
and the request body, and a content type of "text/plain"
.
If the request method is not POST
, we return a 404 Not Found
response.
To test the server, you can use a tool like curl
:
main.rs100 chars3 lines
gistlibby LogSnag