เขียน Web API ด้วย Rust และ Actix-Web หรือ Axum

Sharing is caring!

📌 ทำไมต้อง Rust สำหรับ Web API?

Rust เป็นภาษาที่มีความเร็วสูง ปลอดภัย และเหมาะกับระบบที่ต้องการ performance และ memory safety ระดับสูง การใช้ Rust เขียน Web API จึงเป็นตัวเลือกที่น่าสนใจมาก โดยเฉพาะกับเฟรมเวิร์กอย่าง Actix-Web และ Axum ที่ได้รับความนิยม

🚀 เตรียมโปรเจคด้วย Cargo

cargo new rust-api
cd rust-api
  

🔧 ตัวอย่าง API ด้วย Actix-Web

เพิ่ม dependencies ใน Cargo.toml:




[dependencies]

actix-web = “4”

เขียนไฟล์ main.rs:

use actix_web::{get, App, HttpServer, Responder};

#[get("/")]
async fn hello() -> impl Responder {
    "Hello from Actix-Web!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(hello))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}
  

📦 ตัวอย่าง API ด้วย Axum

เพิ่ม dependencies:




[dependencies]

axum = “0.7” tokio = { version = “1”, features = [“full”] }

สร้าง API ง่าย ๆ:

use axum::{
    routing::get,
    Router,
};

async fn hello() -> &'static str {
    "Hello from Axum!"
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(hello));
    axum::Server::bind(&"127.0.0.1:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}
  

📊 เปรียบเทียบแบบรวบรัด

  • Actix-Web: เร็วสุด ใช้ Actor model
  • Axum: ใช้ง่ายกว่า เหมาะกับมือใหม่ Rust

🧠 สรุปสั้น ๆ

ถ้าคุณต้องการความเร็วสุด ๆ เลือก Actix-Web
ถ้าคุณชอบโค้ดที่อ่านง่าย เลือก Axum
ทั้งคู่ดีเยี่ยม เริ่มจากที่คุณชอบ แล้วเรียนรู้ต่อยอดได้สบาย ๆ


บทความนี้จัดทำโดยทีม poolsawat.com | ใช้เวลาอ่านประมาณ 20 นาที

Leave a Reply

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *