rust way step 8


use actix_web::{get, post, web, App, Error, HttpResponse, HttpServer, Responder};
use actix_files as fs;
use actix_web::{Result};
use actix_files::NamedFile;
use actix_web::HttpRequest;
use serde::Serialize;
use std::{path::PathBuf, string};
use serde::Deserialize;


#[derive(Serialize,Deserialize)]
struct MyObj {
    name: String,
    sex:i32
}

#[get("/obj/{name}")]
async fn test6(name: web::Path<String>) -> Result<impl Responder> {
    let obj = MyObj {
        name: name.to_string(),
        sex:1
    };
    Ok(web::Json(obj))
}



#[get("/file/{filename:.*}")]
async fn test5(req: HttpRequest) -> actix_web::Result<NamedFile> {
    let path: PathBuf = req.match_info().query("filename").parse().unwrap();
    println!("{}",path.to_str().unwrap());
    println!("当前工作目录是: {:?}", std::env::current_dir());
    Ok(NamedFile::open(path)?)
}

#[get("/users/{user_id}/{friend}")] // <- define path parameters
async fn test2(path: web::Path<(u32, String)>) -> Result<String> {
    let (user_id, friend) = path.into_inner();
    Ok(format!("Welcome {}, user_id {}!", friend, user_id))
}


#[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)
}

// http://127.0.0.1:8080/echo1?name=sdf&sex=1
#[get("/echo1")]
async fn test1(info: web::Query<MyObj>) -> String {
    format!("Welcome {} {}!", info.name,info.sex)
}

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

#[derive(Deserialize)]
struct Info {
    username: String,
    pass:String,
}

/// deserialize `Info` from request's body
#[post("/submit")]
async fn submit(info: web::Json<Info>) ->String{

    let json_data = serde_json::json!({
        "name": info.username,
        "pass": info.pass
    });

    let json_string =serde_json::to_string(&json_data).unwrap();
    format!("Welcome {}!", json_string)
}

async fn index() -> String {
    let data ="Hello world!";
    let base64_str: String = base64::encode(&data);
    return format!("Base64 string: {}", base64_str);
}

use actix::{fut::ok, Actor, StreamHandler};
//use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;

/// Define HTTP actor
struct MyWs;

impl Actor for MyWs {
    type Context = ws::WebsocketContext<Self>;
}

/// Handler for ws::Message message
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            _ => (),
        }
    }
}

async fn wstest(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    let resp = ws::start(MyWs {}, &req, stream);
    println!("{:?}", resp);
    resp
}

use actix_web::middleware::Logger;
use env_logger::Env;


/************************************************************* */
use file_hashing::get_hash_file;
use md5::Md5;
use sha1::{Digest, Sha1};

use std::path::Path;

pub fn test_md5<P: AsRef<Path>>(path: P) -> Result<String, std::io::Error> {
    let mut hasher = Md5::new();
    get_hash_file(path, &mut hasher)
}

pub fn test_sha1<P: AsRef<Path>>(path: P) -> Result<String, std::io::Error> {
    let mut hasher = Sha1::new();
    get_hash_file(path, &mut hasher)
}




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


    let path = std::env::current_dir().unwrap().join("2.jpg");

    let actual = test_md5(path.clone());
    if let Ok(a)=actual{
        println!("md5 {}",a);
    }
   
    let actual = test_sha1(path).unwrap();
    println!("sha1 {}",actual);

    env_logger::init_from_env(Env::default().default_filter_or("info"));

    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            .wrap(Logger::new("%a i"))
            .service(hello)
            .service(echo)
            .service(submit)
            .service(test2)
            .service(test1)
            .service(test6)
            .service(test5)
            .service(fs::Files::new("/static", "./static")
            .show_files_listing()
            .use_last_modified(true))
            .route("/hi", web::get().to(manual_hello))
            .service(
                web::scope("/app")  
                .route("/index.html", web::get().to(index)),
            )
            .route("/ws/", web::get().to(wstest))
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

[package]
name = "hello-dioxus"
version = "0.1.0"
edition = "2021"

[dependencies]
reqwest = "0.12.5"
tokio = { version = "1.0.0", features = ["full"] }
actix-web = "4"
actix-files ="0.6.6"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
env_logger ="0.11.3"
actix-web-actors ="4.3.0"
actix="0.13.5"
base64 = "=0.22.1"
file-hashing = "0.1.2"
md-5 = "0.10.6"
sha1 = "0.10.6"
 

相关推荐

  1. 12.<span style='color:red;'>8</span>-1.<span style='color:red;'>8</span>

    12.8-1.8

    2024-07-11 17:28:03      49 阅读
  2. <span style='color:red;'>8</span>. 队列

    8. 队列

    2024-07-11 17:28:03      56 阅读
  3. DevOps(<span style='color:red;'>8</span>)

    DevOps(8)

    2024-07-11 17:28:03      52 阅读
  4. ARMday8

    2024-07-11 17:28:03       31 阅读
  5. Day8.

    2024-07-11 17:28:03       35 阅读
  6. C++-<span style='color:red;'>8</span>

    C++-8

    2024-07-11 17:28:03      29 阅读
  7. <span style='color:red;'>8</span>.Redis

    8.Redis

    2024-07-11 17:28:03      30 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 17:28:03       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 17:28:03       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 17:28:03       58 阅读
  4. Python语言-面向对象

    2024-07-11 17:28:03       69 阅读

热门阅读

  1. MySQL sql_safe_updates参数

    2024-07-11 17:28:03       20 阅读
  2. 表单前端怎么跳转页面:深入探索与实践

    2024-07-11 17:28:03       19 阅读
  3. Mysql中触发器的使用示例

    2024-07-11 17:28:03       22 阅读
  4. 实现前端登录注册功能(有源码)

    2024-07-11 17:28:03       22 阅读
  5. 编程语言:智能制造领域的智慧引擎

    2024-07-11 17:28:03       22 阅读
  6. 通过配置IP路由解决多网卡配置同网段IP的问题

    2024-07-11 17:28:03       23 阅读
  7. ArduPilot开源代码之OpticalFlow_backend

    2024-07-11 17:28:03       23 阅读
  8. Postman API测试覆盖率:全面评估指南

    2024-07-11 17:28:03       22 阅读
  9. OpenHarmony移植小型系统exynos4412(三)

    2024-07-11 17:28:03       22 阅读
  10. 达梦数据库系列—26. DSC主备搭建

    2024-07-11 17:28:03       19 阅读
  11. Mybatis进阶の常用配置&级联查询

    2024-07-11 17:28:03       22 阅读