actix-web初次尝试【待完善】

use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize,Serialize,Debug};
use std::env;

#[derive(Deserialize,Serialize,Debug)]
struct Student{
    name:&'static str,
}

impl Responder for Student{
    type Body = BoxBody;
    fn respond_to(self,_req:&HttpResponse)->HttpResponse<Self::Body>{
        let body = serde_json::to_string(&self).unwrap();
        

        HttpResponse::Ok().content_type(ContentType::json()).body(body)
    }
}
async fn index()->impl Responder{
    Student{name:"hp"}
}

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
    HttpResponse::Ok().body(req_body)
}

async fn manual_hello() -> impl Responder {
    HttpResponse::Ok().body("Hey there!")
}


#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
    format!("Hello {}!", name)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {

    let port = env::var("PORT")
    .unwrap_or_else(|_| "8080".to_string())
    .parse()
    .expect("PORT must be a number");

    HttpServer::new(|| {
        App::new()
            .service(hello)
            .service(echo)
            .service(greet)
            .route("/hey", web::get().to(manual_hello)
            
        )
    })
    .bind(("127.0.0.1", port))?
    .run()
    .await
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值