6. REST API
6.1 健康检查
构建的内容:
POST:/course
EGT: /courses/teacher_id
GET: /courses/teacher_id/courses_id
我们先来编写一下各文件中的代码
/Users/qinjianquan/ws/webservice/src/bin/server1.rs
use actix_web::{web,App,HttpResponse,HttpServer,Responder};
use std::io;
//configure route
pub fn general_routes(cfg:&mut web::ServiceConfig) {
cfg.route("/health",web::get().to(health_check_handler));
}
//configure handler
pub async fn health_check_handler()->impl Responder {
HttpResponse::Ok().json("Actix Web Service is Running!")
}
//instantiate and run HTTP server
#[actix_rt::main]
async fn main() -> io::Result<()> {
//construct App and configure route
let app = move || App::new().configure(general_routes);
//run HTTP server
HttpServer::new(app).bind("127.0.0.1:3000")?.run().await
}
/Users/qinjianquan/ws/webservice/src/bin/teacher-service.rs
use actix_web::{web,App,HttpServer};
use std::io;
use std::sync::Mutex;
#[path = "../handlers.rs"]
mod handlers;
#[path = "../routers.rs"]
mod routers;
#[path = "../state.rs"]
mod state;
use routers::*;
use state::AppState;
#[actix_rt::main]
async fn main() -> io::Result<()> {
let shared_data = web :: Data ::new(AppState{
health_check_response: "I'm OK.".to_string(),
visit_count: Mutex::new(0),
});
let app = move || {
App::new()
.app_data(shared_data.clone())
.configure(general_routes)
};
HttpServer::new(app).bind("127.0.0.1:3030")?.run().await
}
/Users/qinjianquan/ws/webservice/src/handlers.rs
use super::state::AppState;
use actix_web::{web, HttpResponse};
pub async fn health_check_handler(
app_state: web::Data<AppState>
) -> HttpResponse {
let health_check_response = &app_state.health_check_response;
let mut visit_count = app_state.visit_count.lock().unwrap();
let response=
format!("{} {} times",health_check_response, visit_count);
*visit_count +=1;
HttpRes