create a http server and parse cookies and return a json response in rust

To create an HTTP server in Rust, we would need to use a crate such as hyper or actix-web. I will demonstrate using actix-web.

Here is an example code to create an HTTP server in Rust that will parse cookies and return a JSON response:

main.rs
use actix_web::{web, App, HttpResponse, HttpServer};
use serde::Serialize;
use std::collections::HashMap;

// Define a struct to hold the JSON response data
#[derive(Serialize)]
struct JsonResponse {
    message: String,
}

// Define the handler function to be executed when a request is received
async fn index(req: web::HttpRequest) -> HttpResponse {
    // Parse cookies from the request headers
    let mut cookies = HashMap::new();
    if let Some(cookie_header) = req.headers().get("Cookie") {
        for cookie_str in cookie_header.to_str().unwrap().split("; ") {
            let v: Vec<&str> = cookie_str.split('=').collect();
            if v.len() == 2 {
                cookies.insert(v[0].to_string(), v[1].to_string());
            }
        }
    }

    // Create a JSON response
    let response_data = JsonResponse {
        message: "Hello, world!".to_string(),
    };

    // Set the response headers
    let mut response = HttpResponse::Ok();
    response
        .headers_mut()
        .insert(actix_web::http::header::CONTENT_TYPE, "application/json".parse().unwrap());

    // If there are cookies to set, add them to the response headers
    if !cookies.is_empty() {
        for (name, value) in cookies {
            let cookie_str = format!("{}={}; HttpOnly; SameSite=None; Secure", name, value);
            response.headers_mut().insert("Set-Cookie", cookie_str.parse().unwrap());
        }
    }

    // Return the JSON response
    response.body(serde_json::to_string(&response_data).unwrap())
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/", web::get().to(index)))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
1720 chars
54 lines

This code creates an HTTP server that listens on http://127.0.0.1:8080 and responds to all GET requests with a JSON response containing a single message field. It also parses any cookies sent with the request and sets cookies in the response, if necessary.

gistlibby LogSnag