기술나눔

녹의 길 8단계

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

  1. use actix_web::{get, post, web, App, Error, HttpResponse, HttpServer, Responder};
  2. use actix_files as fs;
  3. use actix_web::{Result};
  4. use actix_files::NamedFile;
  5. use actix_web::HttpRequest;
  6. use serde::Serialize;
  7. use std::{path::PathBuf, string};
  8. use serde::Deserialize;
  9. #[derive(Serialize,Deserialize)]
  10. struct MyObj {
  11. name: String,
  12. sex:i32
  13. }
  14. #[get("/obj/{name}")]
  15. async fn test6(name: web::Path<String>) -> Result<impl Responder> {
  16. let obj = MyObj {
  17. name: name.to_string(),
  18. sex:1
  19. };
  20. Ok(web::Json(obj))
  21. }
  22. #[get("/file/{filename:.*}")]
  23. async fn test5(req: HttpRequest) -> actix_web::Result<NamedFile> {
  24. let path: PathBuf = req.match_info().query("filename").parse().unwrap();
  25. println!("{}",path.to_str().unwrap());
  26. println!("当前工作目录是: {:?}", std::env::current_dir());
  27. Ok(NamedFile::open(path)?)
  28. }
  29. #[get("/users/{user_id}/{friend}")] // <- define path parameters
  30. async fn test2(path: web::Path<(u32, String)>) -> Result<String> {
  31. let (user_id, friend) = path.into_inner();
  32. Ok(format!("Welcome {}, user_id {}!", friend, user_id))
  33. }
  34. #[get("/")]
  35. async fn hello() -> impl Responder {
  36. HttpResponse::Ok().body("Hello world!")
  37. }
  38. #[post("/echo")]
  39. async fn echo(req_body: String) -> impl Responder {
  40. HttpResponse::Ok().body(req_body)
  41. }
  42. // http://127.0.0.1:8080/echo1?name=sdf&sex=1
  43. #[get("/echo1")]
  44. async fn test1(info: web::Query<MyObj>) -> String {
  45. format!("Welcome {} {}!", info.name,info.sex)
  46. }
  47. async fn manual_hello() -> impl Responder {
  48. HttpResponse::Ok().body("iam here!")
  49. }
  50. #[derive(Deserialize)]
  51. struct Info {
  52. username: String,
  53. pass:String,
  54. }
  55. /// deserialize `Info` from request's body
  56. #[post("/submit")]
  57. async fn submit(info: web::Json<Info>) ->String{
  58. let json_data = serde_json::json!({
  59. "name": info.username,
  60. "pass": info.pass
  61. });
  62. let json_string =serde_json::to_string(&json_data).unwrap();
  63. format!("Welcome {}!", json_string)
  64. }
  65. async fn index() -> String {
  66. let data ="Hello world!";
  67. let base64_str: String = base64::encode(&data);
  68. return format!("Base64 string: {}", base64_str);
  69. }
  70. use actix::{fut::ok, Actor, StreamHandler};
  71. //use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
  72. use actix_web_actors::ws;
  73. /// Define HTTP actor
  74. struct MyWs;
  75. impl Actor for MyWs {
  76. type Context = ws::WebsocketContext<Self>;
  77. }
  78. /// Handler for ws::Message message
  79. impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
  80. fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {
  81. match msg {
  82. Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
  83. Ok(ws::Message::Text(text)) => ctx.text(text),
  84. Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
  85. _ => (),
  86. }
  87. }
  88. }
  89. async fn wstest(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
  90. let resp = ws::start(MyWs {}, &req, stream);
  91. println!("{:?}", resp);
  92. resp
  93. }
  94. use actix_web::middleware::Logger;
  95. use env_logger::Env;
  96. /************************************************************* */
  97. use file_hashing::get_hash_file;
  98. use md5::Md5;
  99. use sha1::{Digest, Sha1};
  100. use std::path::Path;
  101. pub fn test_md5<P: AsRef<Path>>(path: P) -> Result<String, std::io::Error> {
  102. let mut hasher = Md5::new();
  103. get_hash_file(path, &mut hasher)
  104. }
  105. pub fn test_sha1<P: AsRef<Path>>(path: P) -> Result<String, std::io::Error> {
  106. let mut hasher = Sha1::new();
  107. get_hash_file(path, &mut hasher)
  108. }
  109. #[actix_web::main]
  110. async fn main() -> std::io::Result<()> {
  111. let path = std::env::current_dir().unwrap().join("2.jpg");
  112. let actual = test_md5(path.clone());
  113. if let Ok(a)=actual{
  114. println!("md5 {}",a);
  115. }
  116. let actual = test_sha1(path).unwrap();
  117. println!("sha1 {}",actual);
  118. env_logger::init_from_env(Env::default().default_filter_or("info"));
  119. HttpServer::new(|| {
  120. App::new()
  121. .wrap(Logger::default())
  122. .wrap(Logger::new("%a i"))
  123. .service(hello)
  124. .service(echo)
  125. .service(submit)
  126. .service(test2)
  127. .service(test1)
  128. .service(test6)
  129. .service(test5)
  130. .service(fs::Files::new("/static", "./static")
  131. .show_files_listing()
  132. .use_last_modified(true))
  133. .route("/hi", web::get().to(manual_hello))
  134. .service(
  135. web::scope("/app")
  136. .route("/index.html", web::get().to(index)),
  137. )
  138. .route("/ws/", web::get().to(wstest))
  139. })
  140. .bind(("127.0.0.1", 8080))?
  141. .run()
  142. .await
  143. }

[패키지]
이름 = "안녕-디오수스"
버전 = "0.1.0"
에디션 = "2021"

[종속성]
요청 = "0.12.5"
tokio = { 버전 = "1.0.0", 기능 = ["전체"] }
액틱스-웹 = "4"
액틱스 파일 ="0.6.6"
serde = { 버전 = "1.0", 기능 = ["derive"] }
serde_json = "1.0"
환경 로거 ="0.11.3"
액틱스-웹-액터스 ="4.3.0"
액틱스="0.13.5"
base64 = "=0.22.1"
파일 해싱 = "0.1.2"
md-5 = "0.10.6"
sha1 = "0.10.6"