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
}

你可能感兴趣的:(前端,服务器)