前言
完成一个前后端分离项目,后端技术选型Rust的框架Actix-web,那么用这个框架完成后端代码它的项目目录很重要,今天就来着重介绍一下。
目录结构
下面是自己用Rust Actix-web框架写web后端的目录结构,如图所示:
各个目录作用
1、config模块
config模块主要存放一些配置信息,如网络端口、主机IP等常用信息,如下:
pub struct Server{ pub port:i32,}#[derive(Deserialize,Debug,Clone)]pub struct Mongo{ pub addr:String, pub database:String,}#[derive(Deserialize,Debug,Clone)]pub struct Ip{ pub localhost:String, pub server:String}
2、constant模块
constant主要用于定义常用的常量,如下所示:
pub static COMPANY_COLLECTION:&str= "company";pub static CUSTOMER_COLLECTION:&str = "customer"
3、error模块
error模块主要用于定义错误信息接口,如下:
use std::fmt;use serde::export::Formatter;use toml::de;use std::io;pub enum CommonErrorEnum{ mongodb_error(mongodb::error::Error), common_error(String), toml_error(de::Error),}impl From<:error::error> for CommonErrorEnum{ fn from(error : mongodb::error::Error) -> Self { CommonErrorEnum::mongodb_error(error) }}impl From<:error> for CommonErrorEnum{ fn from(error : de::Error) -> Self { CommonErrorEnum::toml_error(error) }}
4、logger
主要用于定义日志
5、models模块
主要用于定义数据库各个表模型数据信息,如用户账号表:
use serde::{Deserialize, Serialize};use mongodb::{ bson::{doc, Bson, document},};use serde_json::{Result, Value};#[derive(Deserialize,Debug,Clone)]pub struct Account{ userName:Option, password:Option, token:Option}impl Account{ pub fn to_document(&mut self) ->document::Document{ let mut doc = document::Document::new(); doc.insert("userName",Bson::from(self.userName.take().unwrap())); doc.insert("password", Bson::from(self.password.take().unwrap())); doc.insert("token", Bson::from(self.token.take().unwrap_or("".parse().unwrap()))); doc }}
6、server模块
server模块主要定义一些网络请求数据接口信息,如:
use actix_web::{get, web, App, HttpServer, Responder};use log::info;use actix_web::dev::Server;use crate::service::common;use crate::CONF_INSTANCE;pub async fn init() -> std::io::Result { let config = CONF_INSTANCE.get().unwrap(); let server = config.ip.clone().server; HttpServer::new(|| { App::new() .service(web::resource("/v1/common/register").route(web::post().to(common::register))) }) .bind(server)? .run() .await}
7、service模块
service模块用于业务逻辑模块,如注册逻辑:
pub async fn register(vo:web::Json<:customer::customer>) -> Response{ info!("{:?}",vo.0); let mut customer = vo.0.clone(); let uid = Uuid::new_v4(); let mut response = HttpResponse::new(StatusCode::OK); let mongodb_client = MONGODB_INSTANCE.get().clone().unwrap(); let config = CONF_INSTANCE.get().clone().unwrap(); let str_data_base = config.clone().mongo.database; let data_base = mongodb_client.database(str_data_base.as_str()); let company_coll = data_base.collection(constant::COMPANY_COLLECTION); let company_value = vo.0.company.clone().unwrap(); // let company: entity::company::Company = serde_json::from_value(company_value).unwrap(); let company_name = company_value.name.unwrap(); let filter = doc!{"name":company_name}; let mut op_find_company = company_coll.find_one(filter,FindOneOptions::default()).await.unwrap();............
8、util模块
util模块主要用于定义一些工具函数
/// 工具类,后面转成libuse std::time::{SystemTime, UNIX_EPOCH};/// String -> &'static str/// 先是把pub fn string_to_static_str(s: String) -> &'static str { Box::leak(s.into_boxed_str())}/// 获取时间戳pub fn timestamp() -> i64 { let start = SystemTime::now(); let since_the_epoch = start .duration_since(UNIX_EPOCH) .expect("Time went backwards"); let ms = since_the_epoch.as_secs() as i64 * 1000i64 + (since_the_epoch.subsec_nanos() as f64 / 1_000_000.0) as i64; ms}pub fn u8_array_to_string(array:&[u8]) -> String{ use std::fmt::Write; let mut signature_string = String::new(); for a in array.iter() { write!(signature_string, "{:02x}", a); } signature_string}
9、Cargo.toml文件
Cargo.toml文件主要记录软件信息和依赖信息,如下所示:
[package]name = "rust_web"version = "0.1.0"authors = ["huayue430@163.com"]edition = "2018"[dependencies]actix = "0.9.0"actix-codec = "0.2.0"actix-web-actors = "2.0.0"actix-http = "1.0.1"awc = "1.0.1"env_logger = "0.6"