Skip to content

Commit

Permalink
refactor: support server, location and upstream editor
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Mar 28, 2024
1 parent 7bf89d3 commit 8797d60
Show file tree
Hide file tree
Showing 15 changed files with 753 additions and 29 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ target/
/target
.vscode
node_moudles
dist
140 changes: 140 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ dirs = "5.0.1"
env_logger = "0.11.3"
futures-util = "0.3.30"
glob = "0.3.1"
hex = "0.4.3"
hostname = "0.3.1"
http = "1.1.0"
humantime = "2.1.0"
Expand All @@ -34,6 +35,7 @@ once_cell = "1.19.0"
path-absolutize = "3.1.1"
pingora = { version = "0.1.0", default-features = false, features = ["lb"] }
regex = "1.10.4"
rust-embed = { version = "8.3.0", features = ["mime-guess", "compression"] }
serde = "1.0.197"
serde_json = "1.0.114"
snafu = "0.8.2"
Expand Down
1 change: 1 addition & 0 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@
- [ ] start without config
- [ ] static serve for admin
- [ ] status:499 for client abort
- [ ] support get pingap start time
22 changes: 17 additions & 5 deletions src/serve/admin.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
use super::static_file::StaticFile;
use super::Serve;
use crate::config::{self, save_config, LocationConf, ServerConf, UpstreamConf};
use crate::state::State;
use crate::{cache::HttpResponse, config::PingapConf};
use async_trait::async_trait;
use http::Method;
use http::{Method, StatusCode};
use log::error;
use once_cell::sync::Lazy;
use pingora::proxy::Session;
use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use substring::Substring;

pub struct AdminServe {}
#[derive(RustEmbed)]
#[folder = "dist/"]
struct AdminAsset;

pub struct AdminServe {}
pub static ADMIN_SERVE: Lazy<&AdminServe> = Lazy::new(|| &AdminServe {});

#[derive(Serialize, Deserialize)]
Expand Down Expand Up @@ -170,13 +175,20 @@ impl Serve for AdminServe {
_ => self.get_config(category).await,
}
.unwrap_or_else(|err| {
HttpResponse::try_from_json(&ErrorResponse {
println!("{err:?}");
let mut resp = HttpResponse::try_from_json(&ErrorResponse {
message: err.to_string(),
})
.unwrap_or(HttpResponse::unknown_error())
.unwrap_or(HttpResponse::unknown_error());
resp.status = StatusCode::INTERNAL_SERVER_ERROR;
resp
})
} else {
HttpResponse::not_found()
let mut file = path.substring(1, path.len());
if file.is_empty() {
file = "index.html";
}
StaticFile(AdminAsset::get(file)).into()
};
ctx.response_body_size = resp.send(session).await?;
Ok(true)
Expand Down
1 change: 1 addition & 0 deletions src/serve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use async_trait::async_trait;
use pingora::proxy::Session;

mod admin;
mod static_file;

#[async_trait]
pub trait Serve {
Expand Down
47 changes: 47 additions & 0 deletions src/serve/static_file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
use bytes::Bytes;
use hex::encode;
use http::{header, HeaderValue, StatusCode};
use rust_embed::EmbeddedFile;

use crate::cache::HttpResponse;

pub struct StaticFile(pub Option<EmbeddedFile>);

impl From<StaticFile> for HttpResponse {
fn from(value: StaticFile) -> Self {
if value.0.is_none() {
return HttpResponse::not_found();
}
// value 0 is some
let file = value.0.unwrap();
// hash为基于内容生成
let str = &encode(file.metadata.sha256_hash())[0..8];
let mime_type = file.metadata.mimetype();
// 长度+hash的一部分
let entity_tag = format!(r#""{:x}-{str}""#, file.data.len());
// 因为html对于网页是入口,避免缓存后更新不及时
// 因此设置为0
// 其它js,css会添加版本号,因此无影响
let max_age = if mime_type.contains("text/html") {
0
} else {
24 * 3600
};

let mut headers = vec![];
if let Ok(value) = HeaderValue::from_str(mime_type) {
headers.push((header::CONTENT_TYPE, value));
}
if let Ok(value) = HeaderValue::from_str(&entity_tag) {
headers.push((header::ETAG, value));
}

HttpResponse {
status: StatusCode::OK,
body: Bytes::copy_from_slice(&file.data),
max_age: Some(max_age),
headers: Some(headers),
..Default::default()
}
}
}
Loading

0 comments on commit 8797d60

Please sign in to comment.