tiny_http Rust
ตัวอย่างโค้ด Rust สำหรับ tiny_http ที่ตอบคำขอไปยัง /pixel.gif ด้วย GIF ว่าง ซึ่งถอดรหัสเพียงครั้งเดียวตอนเริ่มทำงาน
tiny_http Rust
// Synchronous, no async runtime.
use tiny_http::{Header, Response, Server};
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];
fn main() {
let server = Server::http("0.0.0.0:8080").unwrap();
for request in server.incoming_requests() {
let is_pixel = request.url().split('?').next() == Some("/pixel.gif");
let response = if is_pixel {
Response::from_data(GIF)
.with_header(Header::from_bytes("Content-Type", "image/gif").unwrap())
.with_header(Header::from_bytes("Cache-Control", "no-store").unwrap())
} else {
Response::from_string("Not Found").with_status_code(404)
};
let _ = request.respond(response);
}
}
เรารันตัวอย่างโค้ดนี้และเทียบไบต์ที่ได้กลับมาแล้ว
ตรวจสอบ
curl -sI http://localhost:8080/pixel.gif