init
This commit is contained in:
commit
7d46777f99
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
/target
|
||||||
|
/log
|
1495
Cargo.lock
generated
Normal file
1495
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
28
Cargo.toml
Normal file
28
Cargo.toml
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
[package]
|
||||||
|
name = "poem_demo"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
|
||||||
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
poem = "1.3"
|
||||||
|
poem-openapi = { version = "1.3", features = ["swagger-ui", "email"] }
|
||||||
|
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
||||||
|
tracing = "0.1"
|
||||||
|
tracing-subscriber = { version = "0.3", features = [
|
||||||
|
"time",
|
||||||
|
"env-filter",
|
||||||
|
"registry",
|
||||||
|
"std",
|
||||||
|
] }
|
||||||
|
tracing-appender = "0.2.0"
|
||||||
|
time = { version = "0.3.5", features = [
|
||||||
|
"local-offset",
|
||||||
|
"std",
|
||||||
|
"formatting",
|
||||||
|
"macros",
|
||||||
|
] }
|
||||||
|
slab = "0.4.4"
|
||||||
|
|
||||||
|
lazy_static = "1.4.0"
|
92
src/main.rs
Normal file
92
src/main.rs
Normal file
@ -0,0 +1,92 @@
|
|||||||
|
use std::{collections::HashMap, io};
|
||||||
|
|
||||||
|
use poem::{listener::TcpListener, middleware::AddData, EndpointExt, Route, Server};
|
||||||
|
use poem_openapi::OpenApiService;
|
||||||
|
|
||||||
|
mod user;
|
||||||
|
use time::{format_description, macros::offset};
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tracing::{debug, Level};
|
||||||
|
use tracing_appender::non_blocking::WorkerGuard;
|
||||||
|
use tracing_subscriber::{
|
||||||
|
filter,
|
||||||
|
fmt::{self, time::OffsetTime},
|
||||||
|
prelude::__tracing_subscriber_SubscriberExt,
|
||||||
|
};
|
||||||
|
use user::{api::Api, Token};
|
||||||
|
const FORMAT_STR: &str = "[year]-[month]-[day] [hour]:[minute]:[second]";
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
extern crate lazy_static;
|
||||||
|
|
||||||
|
lazy_static! {
|
||||||
|
static ref CACHE: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::main]
|
||||||
|
async fn main() -> Result<(), std::io::Error> {
|
||||||
|
let _guard = init_log(true);
|
||||||
|
|
||||||
|
tokio::spawn(refresh_token());
|
||||||
|
|
||||||
|
let api_service =
|
||||||
|
OpenApiService::new(Api::default(), "Users", "1.0").server("http://localhost:3000/api");
|
||||||
|
let ui = api_service.swagger_ui();
|
||||||
|
|
||||||
|
Server::new(TcpListener::bind("127.0.0.1:3000"))
|
||||||
|
.run(
|
||||||
|
Route::new()
|
||||||
|
.nest("/api", api_service)
|
||||||
|
.nest("/", ui)
|
||||||
|
.with(AddData::new(Token("token123".to_string()))),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
fn init_log(verbose: bool) -> WorkerGuard {
|
||||||
|
let (non_blocking, _guard) =
|
||||||
|
tracing_appender::non_blocking(tracing_appender::rolling::daily("log", "info.log"));
|
||||||
|
|
||||||
|
let timer = OffsetTime::new(
|
||||||
|
offset!(+8),
|
||||||
|
format_description::parse(FORMAT_STR).expect("parse format error"),
|
||||||
|
);
|
||||||
|
|
||||||
|
let subscriber = tracing_subscriber::registry()
|
||||||
|
.with(filter::Targets::new().with_target(
|
||||||
|
"poem_demo",
|
||||||
|
if verbose { Level::DEBUG } else { Level::INFO },
|
||||||
|
))
|
||||||
|
.with(
|
||||||
|
fmt::Layer::new()
|
||||||
|
.with_timer(timer.clone())
|
||||||
|
.with_writer(io::stdout), // .with_filter(LevelFilter::TRACE),
|
||||||
|
)
|
||||||
|
.with(
|
||||||
|
fmt::Layer::new()
|
||||||
|
.with_timer(timer)
|
||||||
|
.with_ansi(false)
|
||||||
|
.with_writer(non_blocking), // .with_filter(LevelFilter::TRACE),
|
||||||
|
);
|
||||||
|
|
||||||
|
tracing::subscriber::set_global_default(subscriber).expect("Unable to set a global subscriber");
|
||||||
|
|
||||||
|
_guard
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn refresh_token() {
|
||||||
|
let mut interval = 0;
|
||||||
|
|
||||||
|
let mut count = 0;
|
||||||
|
loop {
|
||||||
|
count = count + 1;
|
||||||
|
tokio::time::sleep(tokio::time::Duration::from_secs(interval)).await;
|
||||||
|
debug!("refresh_token... ");
|
||||||
|
|
||||||
|
interval = 5;
|
||||||
|
CACHE
|
||||||
|
.lock()
|
||||||
|
.await
|
||||||
|
.insert("token".to_string(), format!("token{}", count));
|
||||||
|
}
|
||||||
|
}
|
74
src/user/api.rs
Normal file
74
src/user/api.rs
Normal file
@ -0,0 +1,74 @@
|
|||||||
|
use poem::web::Data;
|
||||||
|
use poem_openapi::{param::Path, payload::Json, OpenApi};
|
||||||
|
|
||||||
|
use slab::Slab;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
use crate::CACHE;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(crate) struct Api {
|
||||||
|
users: Mutex<Slab<User>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[OpenApi]
|
||||||
|
impl Api {
|
||||||
|
/// Create a new user
|
||||||
|
#[oai(path = "/users", method = "post", tag = "ApiTags::User")]
|
||||||
|
async fn create_user(&self, user: Json<User>, data: Data<&Token>) -> CreateUserResponse {
|
||||||
|
let Token(token) = data.0;
|
||||||
|
assert_eq!(token, "token123");
|
||||||
|
|
||||||
|
let m_guard = CACHE.lock().await;
|
||||||
|
let rt = m_guard.get(&"token".to_string()).unwrap();
|
||||||
|
info!("refresh_token is {}", rt);
|
||||||
|
|
||||||
|
let mut users = self.users.lock().await;
|
||||||
|
let id = users.insert(user.0) as i64;
|
||||||
|
CreateUserResponse::Ok(Json(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Find user by id
|
||||||
|
#[oai(path = "/users/:user_id", method = "get", tag = "ApiTags::User")]
|
||||||
|
async fn find_user(&self, user_id: Path<i64>) -> FindUserResponse {
|
||||||
|
let users = self.users.lock().await;
|
||||||
|
match users.get(user_id.0 as usize) {
|
||||||
|
Some(user) => FindUserResponse::Ok(Json(user.clone())),
|
||||||
|
None => FindUserResponse::NotFound,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delete user by id
|
||||||
|
#[oai(path = "/users/:user_id", method = "delete", tag = "ApiTags::User")]
|
||||||
|
async fn delete_user(&self, user_id: Path<i64>) -> DeleteUserResponse {
|
||||||
|
let mut users = self.users.lock().await;
|
||||||
|
let user_id = user_id.0 as usize;
|
||||||
|
if users.contains(user_id) {
|
||||||
|
users.remove(user_id);
|
||||||
|
DeleteUserResponse::Ok
|
||||||
|
} else {
|
||||||
|
DeleteUserResponse::NotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update user by id
|
||||||
|
#[oai(path = "/users/:user_id", method = "put", tag = "ApiTags::User")]
|
||||||
|
async fn put_user(&self, user_id: Path<i64>, update: Json<UpdateUser>) -> UpdateUserResponse {
|
||||||
|
let mut users = self.users.lock().await;
|
||||||
|
match users.get_mut(user_id.0 as usize) {
|
||||||
|
Some(user) => {
|
||||||
|
if let Some(name) = update.0.name {
|
||||||
|
user.name = name;
|
||||||
|
}
|
||||||
|
if let Some(password) = update.0.password {
|
||||||
|
user.password = password;
|
||||||
|
}
|
||||||
|
UpdateUserResponse::Ok
|
||||||
|
}
|
||||||
|
None => UpdateUserResponse::NotFound,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
77
src/user/mod.rs
Normal file
77
src/user/mod.rs
Normal file
@ -0,0 +1,77 @@
|
|||||||
|
pub(crate) mod api;
|
||||||
|
|
||||||
|
use poem_openapi::{
|
||||||
|
payload::Json,
|
||||||
|
types::{Email, Password},
|
||||||
|
ApiResponse, Object, Tags,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Tags)]
|
||||||
|
enum ApiTags {
|
||||||
|
/// Operations about user
|
||||||
|
User,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create user schema
|
||||||
|
#[derive(Debug, Object, Clone, Eq, PartialEq)]
|
||||||
|
struct User {
|
||||||
|
/// Id
|
||||||
|
#[oai(read_only)]
|
||||||
|
id: i64,
|
||||||
|
/// Name
|
||||||
|
#[oai(validator(max_length = 64))]
|
||||||
|
name: String,
|
||||||
|
/// Password
|
||||||
|
#[oai(validator(max_length = 32))]
|
||||||
|
password: Password,
|
||||||
|
email: Email,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update user schema
|
||||||
|
#[derive(Debug, Object, Clone, Eq, PartialEq)]
|
||||||
|
struct UpdateUser {
|
||||||
|
/// Name
|
||||||
|
name: Option<String>,
|
||||||
|
/// Password
|
||||||
|
password: Option<Password>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(ApiResponse)]
|
||||||
|
enum CreateUserResponse {
|
||||||
|
/// Returns when the user is successfully created.
|
||||||
|
#[oai(status = 200)]
|
||||||
|
Ok(Json<i64>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(ApiResponse)]
|
||||||
|
enum FindUserResponse {
|
||||||
|
/// Return the specified user.
|
||||||
|
#[oai(status = 200)]
|
||||||
|
Ok(Json<User>),
|
||||||
|
/// Return when the specified user is not found.
|
||||||
|
#[oai(status = 404)]
|
||||||
|
NotFound,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(ApiResponse)]
|
||||||
|
enum DeleteUserResponse {
|
||||||
|
/// Returns when the user is successfully deleted.
|
||||||
|
#[oai(status = 200)]
|
||||||
|
Ok,
|
||||||
|
/// Return when the specified user is not found.
|
||||||
|
#[oai(status = 404)]
|
||||||
|
NotFound,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(ApiResponse)]
|
||||||
|
enum UpdateUserResponse {
|
||||||
|
/// Returns when the user is successfully updated.
|
||||||
|
#[oai(status = 200)]
|
||||||
|
Ok,
|
||||||
|
/// Return when the specified user is not found.
|
||||||
|
#[oai(status = 404)]
|
||||||
|
NotFound,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct Token(pub(crate) String);
|
Loading…
Reference in New Issue
Block a user