基于Rust语言的Rocket框架和Sqlx库开发WebAPI项目记录(三)

  • 公共模块

在src目录新建common文件夹

在common文件夹里依次新建db.rs、jwt.rs、mistake.rs、utils.rs、mod.rs

目录结构如下:

project

|—src

        |—params   //封装参数结构体模块

                 |—req.rs    //封装请求参数结构体

                 |—resp.rs  //封装返回数据结构体

                 |—result_parse.rs  //解析返回参数结构体

                 |—mod.rs    //导出模块       

        |—common    //公共模块

                |—db.rs    //构造数据库连接池

                |—jwt.rs   //处理token

                |—mistake.rs  //处理错误

                |—util.rs  //工具函数

                |—mod.rs  //导出模块

db.rs代码:

use rocket_db_pools::Database;
use rocket_db_pools::sqlx;

//构造连接池
#[derive(Database,Clone)]
//prodb为postgresql里创建的数据库名
#[database("prodb")]
pub struct Prodb(sqlx::PgPool);


jwt.rs代码:


use rocket::serde::{Deserialize,Serialize};
use jsonwebtoken::{encode, EncodingKey, Header,decode, DecodingKey, Validation};
use rocket::http::Status;
use rocket::request::{FromRequest, Outcome};
use rocket::serde::json::{Json,Value,json};
use std::time::{SystemTime, UNIX_EPOCH};
use rocket::post;


use crate::params::req::Userparam;

#[derive(Deserialize, Serialize)]
#[serde(crate = "rocket::serde")]
pub struct Claims {
    pub sub: String,
    pub exp: u64,
    pub user: Userparam
}

pub const KEY: &[u8] = b"secret";

#[derive(Debug)]
pub struct Token{
   pub uname: String,
   pub id:String

}
// Bearer Token
impl Token {
    fn from_request(header: &str) -> Option<Token> {
        let split_vec = header.split_whitespace().collect::<Vec<_>>();
        if split_vec.len() != 2 {
            return None;
        }
        if split_vec[0] != "Bearer" {
            return None;
        }
        Self::from_jwt(split_vec[1])
    }
    fn from_jwt(token_string: &str) -> Option<Token> {
        let mut val = Validation::default();
        val.sub = Some("1qaz2wsx@2024.com!qaz@wsx".to_string());
        match decode::<Claims>(token_string, &DecodingKey::from_secret(KEY), &val) {
            Ok(c) => {
              //  println!("==c.claims.user=={:?}",c.claims.user);
            //解析token获取用户信息
            let user=Token{
                uname:c.claims.user.uname,
                id:c.claims.user.id
            };
                return Some(user);
              
            
           }
            Err(_) => None,
        }
    }

}

#[rocket::async_trait]
impl<'r> FromRequest<'r> for Token {
    type Error = ();
    async fn from_request(request: &'r rocket::Request<'_>) -> Outcome<Self, Self::Error> {
        let header_auth = request.headers().get_one("Authorization");
        if let Some(header_auth) = header_auth {
            if let Some(auth) = Self::from_request(header_auth) {
                return Outcome::Success(auth);
            }
        }
        Outcome::Error((Status::Unauthorized, ()))
    }
}

#[post("/gettoken",data="<userparam>")]
//生成token
pub async fn get_token(userparam : Json<Userparam>) -> Value {
    let user = userparam.into_inner();
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let token = match encode(
            &Header::default(),
            &Claims {
                sub: String::from("1qaz2wsx@2024.com!qaz@wsx"),
                exp: timestamp + 21600000,
                user:user
            },
            &EncodingKey::from_secret(KEY),
        ) {
            Ok(t) => t,
            Err(_) => panic!(),
        };
        json!({ "token": token })
    
}

mistake.rs代码:

use rocket::serde::json::Json;
use rocket::catch;

use crate::params::resp;

#[catch(401)]
pub fn un_auth()->Json<resp::Resp>{

    Json(
        resp::Resp { code:0,
        message:"未获授权!".to_string(),
      })
}

#[catch(404)]
pub fn un_find()->Json<resp::Resp>{

    Json(
        resp::Resp { code:0,
        message:"接口未找到!".to_string(),
      })
}

#[catch(500)]
pub fn on_error()->Json<resp::Resp>{

    Json(
        resp::Resp { code:0,
        message:"内部服务器错误!".to_string(),
      })
}

#[catch(400)]
pub fn bad_request()->Json<resp::Resp>{

    Json(
        resp::Resp { code:0,
        message:"请求缺少参数或请求方式错误!".to_string(),
      })
}

#[catch(422)]
pub fn un_processable()->Json<resp::Resp>{

    Json(
        resp::Resp { code:0,
        message:"请求参数不全!".to_string(),
      })
}

utils.rs代码:

use uuid::Uuid;
use chrono::{NaiveDateTime,DateTime,Local,ParseError,NaiveDate};



//获取uuid
pub fn get_uuid() -> String {
    
    let my_uuid = Uuid::new_v4();
    my_uuid.to_string()
    
    
}

//获取当前日期时间(日期格式)
pub fn get_datetime()->Result<DateTime<Local>,ParseError>{
    Ok(Local::now())
}

//获取当前日期(字符串格式)
pub fn get_date()->String{
    Local::now().format("%Y-%m-%d").to_string()
}

//字符串转日期时间
pub fn str_to_datetime(str:&str)->Result<NaiveDateTime,ParseError>{

    let format="%Y-%m-%d %H:%M:%S.3f";
    let datetime=NaiveDateTime::parse_from_str(str, format)?;
    Ok(datetime)
}

//字符串转日期
pub fn str_to_date(str:&str)->Result<NaiveDate,ParseError>{

    let format="%Y-%m-%d";
    let date=NaiveDate::parse_from_str(str, format)?;
    Ok(date)
}

//日期转字符串
pub fn date_to_str(date:NaiveDate)->String{

    date.format("%Y-%m-%d").to_string()
}

//日期时间转字符串
pub fn datetime_to_str(date:NaiveDateTime)->String{

    date.format("%Y-%m-%d %H:%M:%S.3f").to_string()
}

mod.rs代码:


//数据库
pub mod db;
//工具
pub mod utils;
//jsonwebtoken
pub mod jwt;
//错误
pub mod mistake;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值