rustRust HTTP server example
A basic Rust HTTP server example can be written using the hyper library. The following ## Code example creates a server that listens on port 8080 and responds with a "Hello World" message when a request is received:
use hyper::{Body, Request, Response, Server};
use hyper::rt::{self, Future};
use hyper::service::service_fn_ok;
fn hello_world(_req: Request<Body>) -> Response<Body> {
Response::new(Body::from("Hello, World!"))
}
fn main() {
let addr = ([127, 0, 0, 1], 8080).into();
let server = Server::bind(&addr)
.serve(|| service_fn_ok(hello_world))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
rt::run(server);
}
The ## Code example creates a server that listens on port 8080 and responds with a "Hello World" message when a request is received. The Server::bind
method is used to bind the server to the given address, and the serve
method is used to specify the service that should be used to handle requests. The service_fn_ok
function is used to create a service that will handle requests and return a response. Finally, the run
method is used to start the server.
Output example:
Listening on http://127.0.0.1:8080
Explanation
The ## Code example creates a server that listens on port 8080 and responds with a "Hello World" message when a request is received. The Server::bind
method is used to bind the server to the given address, and the serve
method is used to specify the service that should be used to handle requests. The service_fn_ok
function is used to create a service that will handle requests and return a response. Finally, the run
method is used to start the server.
Helpful links
More of Rust
- How to match whitespace with a regex in Rust?
- How to split a string with Rust regex?
- How to use regex to match a double quote in Rust?
- How to use non-capturing groups in Rust regex?
- How to use regex with bytes in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to replace all matches using Rust regex?
- How to use regex to match a group in Rust?
- How to get a capture group using Rust regex?
See more codes...