忙活了一整天,终于使用rust改写了之前python的API接口服务:下面是代码和依赖。
main.rs
use axum::{
extract::Path as routepath,
response::Json,
routing::{get, delete},
Router,
};
use serde_json::{json, Value};
use std::io::BufReader;
mod mytool;
static FILENAME: &str = "D:\\rust\\helloworld\\static\\devicelist.txt";
#[tokio::main]
async fn main() {
// build our application with a single route
let app = Router::new()
.route("/getdevicelist", get(getDeviceList))
.route("/addDeviceCode/:code", get(addDeviceCode))
.route("/delDeviceCode/:code", delete(delDeviceCode));
// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:9527".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
async fn getDeviceList() -> Json<Value> {
let file_vec = mytool::openfile(FILENAME);
let json_data = json!({
"code":200,
"count":file_vec.len(),
"data":file_vec
});
Json(json_data)
}
async fn addDeviceCode(code: routepath<String>) -> Json<Value> {
let file_vec: Vec<String> = mytool::openfile(FILENAME);
println!("addDeviceCode:{:?}", code);
let channelcode: &str = code.as_str();
if channelcode.is_empty() || channelcode.len() != 19 {
Json(json!({"code":"400","message":"code is empty"}))
} else {
let mut file_vec_clone = file_vec.clone();
file_vec_clone.push(code.to_string());
mytool::write_lines_to_file(FILENAME, file_vec_clone.clone());
Json(json!({"code":"200","message":"success"}))
}
}
async fn delDeviceCode(code: routepath<String>) -> Json<Value> {
if code.as_str().is_empty() || code.as_str().len() != 19 {
Json(json!({"code":"400","message":"code is empty"}))
} else {
let result = mytool::detete_device_code(FILENAME, code.as_str());
if result == 0 {
Json(json!({"code":"400","message":"Fail"}))
}else {
Json(json!({"code":"200","message":"success"}))
}
}
}
mytool.rs
use std::fs;
use std::io::{self,BufRead, BufReader,BufWriter,Write};
pub fn openfile(path: &str) -> Vec<String>{
println!("{}", path);
let file = BufReader::new(fs::File::open(path).unwrap());
let mut lines = Vec::new();
for line in file.lines() {
let lines_str = line.unwrap();
println!("{}", lines_str);
lines.push(lines_str);
}
lines
}
pub fn write_lines_to_file(file_path: &str, codelist: Vec<String>) -> io::Result<()> {
let file = fs::File::create(file_path)?;
let mut writer = BufWriter::new(file);
for line in codelist {
writer.write_all(line.as_bytes())?;
writer.write_all(b"\n")?;
}
writer.flush()?;
Ok(())
}
pub fn detete_device_code(file_path: &str,code:&str)->i64{
let mut Veclist = openfile(file_path);
if Veclist.len()==0{
return 0;
}
Veclist = Veclist.into_iter().filter(|x| x != code).collect();
write_lines_to_file(file_path,Veclist);
return 1;
}
Cargo.toml
[package]
name = "helloworld"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
axum = "0.4.3"
tokio = { version = "1.15.0", features = ["full"]}
serde_json = "1.0.68"
期间碰壁不少,最终还是在服务器上运行起来了。
在服务器使用的是nohup cargo run 来常驻后台,但是当我想要找这个进程时,使用ps aux| grep "cargo run"却没有找到.
最后因为cargo run 实际上是执行的target/debug(release)下的二进制文件,所以直接grep这个文件名或者工程名就找到了。
网友评论