emptygif
மொழி: தமிழ்

அனைத்து மொழிகளும் ஃப்ரேம்வொர்க்குகளும்

hyper Rust

/pixel.gif க்கு வரும் ரெக்வெஸ்ட்களுக்கு empty GIF மூலம் பதிலளிக்கும், hyper க்கான Rust ஸ்னிப்பெட். GIF ஸ்டார்ட்அப்பில் ஒருமுறை மட்டுமே டீகோட் செய்யப்படுகிறது.

hyper Rust

இன்ஸ்டால்
cargo add hyper --features server,http1 && cargo add hyper-util --features tokio && cargo add http-body-util bytes && cargo add tokio --features full
ஃபைல்
src/main.rs
ரன்
cargo run --release
use std::convert::Infallible;

use bytes::Bytes;
use http_body_util::Full;
use hyper::body::Incoming;
use hyper::server::conn::http1;
use hyper::service::service_fn;
use hyper::{Request, Response, StatusCode, header};
use hyper_util::rt::TokioIo;
use tokio::net::TcpListener;

const GIF: &[u8] = &[0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x21, 0xf9, 0x04, 0x01, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02, 0x02, 0x44, 0x01, 0x00, 0x3b];

async fn handle(req: Request<Incoming>) -> Result<Response<Full<Bytes>>, Infallible> {
    let response = if req.uri().path() == "/pixel.gif" {
        Response::builder()
            .header(header::CONTENT_TYPE, "image/gif")
            .header(header::CACHE_CONTROL, "no-store")
            .body(Full::new(Bytes::from_static(GIF)))
    } else {
        Response::builder()
            .status(StatusCode::NOT_FOUND)
            .body(Full::default())
    };
    Ok(response.unwrap())
}

#[tokio::main]
async fn main() -> std::io::Result<()> {
    let listener = TcpListener::bind("0.0.0.0:8080").await?;
    loop {
        let (stream, _) = listener.accept().await?;
        tokio::spawn(async move {
            let service = service_fn(handle);
            if let Err(err) = http1::Builder::new()
                .serve_connection(TokioIo::new(stream), service)
                .await
            {
                eprintln!("connection error: {err}");
            }
        });
    }
}

இந்த ஸ்னிப்பெட்டை ரன் செய்து, அது திருப்பித் தந்த பைட்களை ஒப்பிட்டுப் பார்த்தோம்.

சரிபார்

curl -sI http://localhost:8080/pixel.gif

அதிகாரப்பூர்வ சைட்: hyper

Rust இல் மேலும்