create a http server with a specific route in rust

To create an HTTP server in Rust with a specific route, we can use the Rocket web framework. Here's an example:

main.rs
// Import necessary packages
#![feature(proc_macro_hygiene, decl_macro)]
#[macro_use] extern crate rocket;

// Define our specific route
#[get("/hello")]
fn hello() -> &'static str {
    "Hello, world!"
}

fn main() {
    // Launch the server
    rocket::ignite().mount("/", routes![hello]).launch();
}
303 chars
15 lines

In this example, we are defining a /hello route using the hello function. The routes! macro is used to register our route with the Rocket server.

With Rocket installed, you can build and run this program with:

main.rs
$ cargo run
12 chars
2 lines

Now, if you open your browser and navigate to http://localhost:8000/hello, you should see the text "Hello, world!" displayed in your browser.

related categories

gistlibby LogSnag