To create an HTTP server with a specific route and a specific status code in Rust, you can use the hyper
crate, which provides a low-level API for building HTTP servers.
Here is an example code that creates an HTTP server with a single route /hello
that responds with a 200 status code and a message of "Hello, World!":
main.rs644 chars25 lines
In this code, the hello
function is the handler for the /hello
route. It takes a Request
object as an argument and returns a Response
object. The Response
object is created using the hyper::Response::new
constructor, which takes the body of the response as an argument.
The make_service_fn
function creates a closure that returns a service for each connection. The service_fn
function creates a service that handles each request by calling the hello
function.
The Server::bind
function creates a new Server
instance that listens on the specified address and serves the provided service.
When you run this code, the server will listen on http://127.0.0.1:3000
. If you make a GET
request to http://127.0.0.1:3000/hello
, you should receive a response with a 200 status code and the message "Hello, World!".
gistlibby LogSnag