Browse Source

actix web

marion 4 years ago
parent
commit
9b0b123dcf

File diff suppressed because it is too large
+ 677 - 139
Cargo.lock


+ 8 - 2
Cargo.toml

@@ -7,5 +7,11 @@ edition = "2018"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-reqwest = { version = "0.10.4", features = ["blocking", "json"] }
-tokio = { version = "0.2.13", features = ["full"] }
+actix-web = "2"
+actix-rt = "1"
+actix-files = "0.2"
+
+env_logger = "0.7"
+serde = { version = "1.0", features = ["derive"] }
+serde_json = "1.0"
+bytes = "0.5"

+ 35 - 0
src/actix_test/controllers/home_controller.rs

@@ -0,0 +1,35 @@
+use actix_web::http::{StatusCode};
+use actix_web::web::{ServiceConfig, resource as r, get, post};
+use actix_web::{HttpRequest, HttpResponse, Result, Error};
+use bytes::Bytes;
+
+use crate::actix_test::models::user_info::UserInfo;
+
+/// route config
+pub fn config(cfg: &mut ServiceConfig) {
+    cfg
+        .service(
+            r("/")
+                .route(get().to(index))
+                .route(post().to(index_post))
+        );
+}
+
+/// index page
+async fn index(req: HttpRequest) -> Result<HttpResponse> {
+    println!("{:?}", req);
+
+    // response
+    Ok(HttpResponse::build(StatusCode::OK)
+        .content_type("text/html; charset=utf-8")
+        .body(include_str!("../../../static/index.html")))
+}
+
+/// http post example
+//async fn index_post(item: web::Json<UserInfo>) -> Result<HttpResponse, Error> { // need json Content-Type
+async fn index_post(body: Bytes) -> Result<HttpResponse, Error> {
+    //let obj = item.0;
+    let obj = serde_json::from_slice::<UserInfo>(&body)?;
+    println!("model: {:?}", &obj);
+    Ok(HttpResponse::Ok().json(obj)) // <- send response
+}

+ 2 - 0
src/actix_test/controllers/mod.rs

@@ -0,0 +1,2 @@
+pub mod test_controller;
+pub mod home_controller;

+ 22 - 0
src/actix_test/controllers/test_controller.rs

@@ -0,0 +1,22 @@
+use actix_web::web::{ServiceConfig, scope, resource as r, get};
+
+/// route config
+pub fn config(cfg: &mut ServiceConfig) {
+    cfg
+        .service(
+            scope("/test")
+                .service(r("/imgood").route(get().to(im_good)))
+        );
+}
+
+/// health check
+// Actix web request param binding:
+// request object: req: HttpRequest    println!("{:?}", req) req.headers().get("headerKey")
+// path: web::Path<(param0Type, paramNType)>    path.0 path.N
+// query: web::Query<HashMap<String, String>>    query.get("queryStringOrFromParamKey")
+// item: web::Json<MyObj>    item.0
+// body: bytes::Bytes
+// mut payload: web::Payload
+async fn im_good() -> String {
+    format!("{{\"status\":0,\"msg\":\"success\"}}")
+}

+ 58 - 0
src/actix_test/mod.rs

@@ -0,0 +1,58 @@
+// [dependencies]
+// actix-web = "2"
+// actix-rt = "1"
+// actix-files = "0.2"
+//
+// env_logger = "0.7"
+// serde = { version = "1.0", features = ["derive"] }
+// serde_json = "1.0"
+// bytes = "0.5"
+
+mod controllers;
+mod models;
+
+// #[macro_use]
+// extern crate actix_web;
+
+use actix_files as fs;
+use actix_web::http::{StatusCode};
+use actix_web::web::{resource as r, route, get};
+use actix_web::{get, guard, middleware, App, HttpResponse, HttpServer, Result};
+
+/// favicon handler
+#[get("/favicon")]
+async fn favicon() -> Result<fs::NamedFile> {
+    Ok(fs::NamedFile::open("static/favicon.ico")?)
+}
+
+/// 404 handler
+async fn p404() -> Result<fs::NamedFile> {
+    Ok(fs::NamedFile::open("static/404.html")?.set_status_code(StatusCode::NOT_FOUND))
+}
+
+#[actix_rt::main]
+pub async fn http_listener() -> std::io::Result<()> {
+    std::env::set_var("RUST_LOG", "actix_web=info,actix_server=info");
+    env_logger::init();
+
+    HttpServer::new(|| {
+        App::new()
+            .wrap(middleware::Logger::default())
+            .service(favicon)
+            .service(fs::Files::new("/static", "static").index_file("/"))
+            // default
+            .default_service(
+                // 404 for GET request
+                r("")
+                    .route(get().to(p404))
+                    // all requests that are not `GET`
+                    .route(
+                        route()
+                            .guard(guard::Not(guard::Get()))
+                            .to(HttpResponse::MethodNotAllowed),
+                    ),
+            )
+            .configure(controllers::test_controller::config)
+            .configure(controllers::home_controller::config)
+    }).bind("127.0.0.1:8080")?.run().await
+}

+ 1 - 0
src/actix_test/models/mod.rs

@@ -0,0 +1 @@
+pub mod user_info;

+ 7 - 0
src/actix_test/models/user_info.rs

@@ -0,0 +1,7 @@
+use serde::{Deserialize, Serialize};
+
+#[derive(PartialEq, Debug, Serialize, Deserialize)]
+pub struct UserInfo {
+    pub name: String,
+    pub number: i32,
+}

+ 5 - 3
src/main.rs

@@ -5,16 +5,18 @@
 // mod random_test;
 // mod keygen_test;
 // mod qr_code_test;
-mod spider_test;
+// mod spider_test;
+mod actix_test;
 
 // 将其他模块的成员声明为当前模块直接可用的,等同于java的静态引用
 // 若省略这句,使用时就需要加上模块名,如random_test::Random
 // use self::random_test::{test, Random};
 
-fn main() {
+fn main() -> std::io::Result<()> {
     // random_test::test();
     // keygen_test::test();
     // qr_code_test::test(2, 3);
-    spider_test::test("https://www.baidu.com").unwrap();
+    // spider_test::test("https://www.baidu.com").unwrap();
+    actix_test::http_listener()
 }
 

+ 4 - 0
src/spider_test/mod.rs

@@ -1,3 +1,7 @@
+// [dependencies]
+// reqwest = { version = "0.10.4", features = ["blocking", "json"] }
+// tokio = { version = "0.2.13", features = ["full"] }
+
 #[tokio::test]
 async fn test_async() -> Result<(), Box<dyn std::error::Error>> {
     let resp = reqwest::get("https://httpbin.org/ip").await?

+ 10 - 0
static/404.html

@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <title>404 Not Found</title>
+        <link rel="shortcut icon" type="image/x-icon" href="/favicon"/>
+    </head>
+    <body>
+        <h1>404 Not Found</h1>
+    </body>
+</html>

BIN
static/actixLogo.png


BIN
static/favicon.ico


+ 10 - 0
static/index.html

@@ -0,0 +1,10 @@
+<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <title>hello actix</title>
+        <link rel="shortcut icon" type="image/x-icon" href="/favicon" />
+    </head>
+    <body>
+        <h1><img width="30px" height="30px" src="/static/actixLogo.png" /> Welcome!</h1>
+    </body>
+</html>

Some files were not shown because too many files changed in this diff