return a json response from a http server with a specific status code in rust

To return a JSON response from an HTTP server with a specific status code in Rust, you can use the http and serde_json crates.

Here's an example code that demonstrates how to do this:

main.rs
use http::{Response, StatusCode};
use serde::Serialize;

#[derive(Serialize)]
struct MyResponse {
    message: String,
}

fn my_handler() -> Response<String> {
    let data = MyResponse {
        message: "Hello, World!".to_owned(),
    };

    let json_data = serde_json::to_string(&data).unwrap();

    Response::builder()
        .status(StatusCode::OK)
        .header("Content-Type", "application/json")
        .body(json_data)
        .unwrap()
}
454 chars
22 lines

In this example code, MyResponse is a simple struct that we want to return as JSON. We implement the Serialize trait from serde to enable JSON serialization.

The my_handler function returns an http Response object with a status code of StatusCode::OK.

We set the Content-Type header to application/json to indicate that we're returning JSON data.

Finally, we serialize our MyResponse object to JSON using the serde_json::to_string function, and pass the resulting string as the body of the response.

To use this example code, you would need to implement an HTTP server using a crate like hyper or rocket, and define a route that calls the my_handler function to return the JSON response.

gistlibby LogSnag