feat: 新增 web 端 — axum HTTP 服务 + Docker 化
新增 workspace crate : - axum 0.8 + tokio 异步 HTTP 服务 - / → 嵌入式 HTML 页面(输入→实时预览→下载/复制) - /api/qr?text=&level=M&margin=4&size=8 → PNG - Dockerfile: rust-alpine 多阶段构建,镜像仅 ~12MB - Cargo.toml: workspace 新增 web 成员 部署: docker build -t qrgen-web -f web/Dockerfile . docker run -p 3000:3000 qrgen-web Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "qrgen-web"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
|
||||
[dependencies]
|
||||
qr-core = { path = "../core" }
|
||||
axum = "0.8"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tower-http = { version = "0.6", features = ["cors"] }
|
||||
@@ -0,0 +1,18 @@
|
||||
# ── 构建阶段 ──
|
||||
FROM rust:1.95-alpine AS builder
|
||||
|
||||
RUN apk add --no-cache musl-dev
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
RUN cargo build --release -p qrgen-web
|
||||
|
||||
# ── 运行阶段 ──
|
||||
FROM alpine:3.22
|
||||
|
||||
RUN apk add --no-cache tzdata
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
COPY --from=builder /app/target/release/qrgen-web /usr/local/bin/qrgen-web
|
||||
|
||||
EXPOSE 3000
|
||||
CMD ["qrgen-web"]
|
||||
@@ -0,0 +1,80 @@
|
||||
use axum::{
|
||||
extract::Query,
|
||||
http::{header, StatusCode},
|
||||
response::{Html, IntoResponse},
|
||||
routing::get,
|
||||
Router,
|
||||
};
|
||||
use qr_core::qr::{QrCode, QrConfig, VersionMode};
|
||||
use qr_core::version::EcLevel;
|
||||
use serde::Deserialize;
|
||||
|
||||
/// GET /api/qr 查询参数
|
||||
#[derive(Deserialize)]
|
||||
struct QrParams {
|
||||
text: String,
|
||||
#[serde(default = "default_level")]
|
||||
level: String,
|
||||
#[serde(default = "default_margin")]
|
||||
margin: u8,
|
||||
#[serde(default = "default_size")]
|
||||
size: u8,
|
||||
}
|
||||
|
||||
fn default_level() -> String { "M".into() }
|
||||
fn default_margin() -> u8 { 4 }
|
||||
fn default_size() -> u8 { 8 }
|
||||
|
||||
fn parse_level(s: &str) -> Result<EcLevel, String> {
|
||||
match s.to_uppercase().as_str() {
|
||||
"L" => Ok(EcLevel::L),
|
||||
"M" => Ok(EcLevel::M),
|
||||
"Q" => Ok(EcLevel::Q),
|
||||
"H" => Ok(EcLevel::H),
|
||||
_ => Err(format!("无效纠错级别: {},支持 L/M/Q/H", s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 首页 HTML(编译期嵌入)
|
||||
async fn index() -> Html<&'static str> {
|
||||
Html(include_str!("templates/index.html"))
|
||||
}
|
||||
|
||||
/// QR 码生成 API → PNG 图片
|
||||
async fn generate_qr(Query(params): Query<QrParams>) -> impl IntoResponse {
|
||||
let level = match parse_level(¶ms.level) {
|
||||
Ok(l) => l,
|
||||
Err(e) => return (StatusCode::BAD_REQUEST, e).into_response(),
|
||||
};
|
||||
|
||||
let config = QrConfig {
|
||||
level,
|
||||
version: VersionMode::Auto,
|
||||
margin: params.margin,
|
||||
};
|
||||
|
||||
let qr = match QrCode::encode(¶ms.text, config) {
|
||||
Ok(q) => q,
|
||||
Err(e) => return (StatusCode::BAD_REQUEST, e).into_response(),
|
||||
};
|
||||
|
||||
let png = match qr.to_png_bytes(params.size) {
|
||||
Ok(b) => b,
|
||||
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()).into_response(),
|
||||
};
|
||||
|
||||
([(header::CONTENT_TYPE, "image/png")], png).into_response()
|
||||
}
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let app = Router::new()
|
||||
.route("/", get(index))
|
||||
.route("/api/qr", get(generate_qr));
|
||||
|
||||
let addr = "0.0.0.0:3000";
|
||||
println!("QRGen Web → http://{}", addr);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>QRGen Web</title>
|
||||
<style>
|
||||
:root { color-scheme: light dark; }
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
min-height: 100vh; display: flex; align-items: center; justify-content: center;
|
||||
background: #f5f5f5;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) { body { background: #1a1a2e; color: #e0e0e0; } }
|
||||
.card {
|
||||
background: #fff; border-radius: 16px; padding: 32px;
|
||||
box-shadow: 0 2px 16px rgba(0,0,0,.08); max-width: 420px; width: 90%;
|
||||
display: flex; flex-direction: column; gap: 16px;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) { .card { background: #16213e; } }
|
||||
h1 { font-size: 20px; font-weight: 600; text-align: center; }
|
||||
textarea, input, select {
|
||||
width: 100%; padding: 10px 12px; border: 1px solid #ddd;
|
||||
border-radius: 8px; font-size: 14px; background: #fafafa;
|
||||
font-family: inherit;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
textarea, input, select { background: #0f3460; border-color: #1a1a2e; color: #e0e0e0; }
|
||||
}
|
||||
textarea { resize: vertical; min-height: 80px; }
|
||||
.row { display: flex; gap: 12px; align-items: center; }
|
||||
.row label { font-size: 13px; white-space: nowrap; min-width: 60px; }
|
||||
button {
|
||||
padding: 10px 24px; border: none; border-radius: 8px;
|
||||
background: #2563eb; color: #fff; font-size: 14px; font-weight: 500;
|
||||
cursor: pointer; transition: background .15s;
|
||||
}
|
||||
button:hover { background: #1d4ed8; }
|
||||
button:disabled { opacity: .4; cursor: not-allowed; }
|
||||
.preview {
|
||||
display: flex; justify-content: center; padding: 16px;
|
||||
background: #fff; border-radius: 12px; min-height: 200px;
|
||||
align-items: center;
|
||||
}
|
||||
.preview img { max-width: 240px; }
|
||||
.info { font-size: 12px; color: #888; text-align: center; }
|
||||
.actions { display: flex; gap: 8px; }
|
||||
.actions button { flex: 1; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
<h1>QRGen Web</h1>
|
||||
<textarea id="text" placeholder="输入要编码的内容…"></textarea>
|
||||
<div class="row">
|
||||
<label>纠错级别</label>
|
||||
<select id="level">
|
||||
<option value="L">L — 7%</option>
|
||||
<option value="M" selected>M — 15%</option>
|
||||
<option value="Q">Q — 25%</option>
|
||||
<option value="H">H — 30%</option>
|
||||
</select>
|
||||
<label>边距</label>
|
||||
<input id="margin" type="number" value="4" min="1" max="20" style="width:64px">
|
||||
</div>
|
||||
<div class="row">
|
||||
<label>模块大小</label>
|
||||
<input id="size" type="range" value="8" min="2" max="20" oninput="document.getElementById('sizeVal').textContent=this.value">
|
||||
<span id="sizeVal" style="font-size:13px">8</span>px
|
||||
</div>
|
||||
<div class="preview" id="preview">
|
||||
<span style="color:#999">输入内容生成 QR 码</span>
|
||||
</div>
|
||||
<div class="info" id="info"></div>
|
||||
<div class="actions">
|
||||
<button id="btnDownload" disabled>下载 PNG</button>
|
||||
<button id="btnCopy" disabled>复制链接</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const textEl = document.getElementById('text');
|
||||
const levelEl = document.getElementById('level');
|
||||
const marginEl = document.getElementById('margin');
|
||||
const sizeEl = document.getElementById('size');
|
||||
const preview = document.getElementById('preview');
|
||||
const info = document.getElementById('info');
|
||||
let timer, currentUrl = '';
|
||||
|
||||
function update() {
|
||||
const text = textEl.value.trim();
|
||||
if (!text) { preview.innerHTML='<span style="color:#999">输入内容生成 QR 码</span>'; info.textContent=''; return; }
|
||||
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(async () => {
|
||||
const p = new URLSearchParams({ text, level: levelEl.value, margin: marginEl.value, size: sizeEl.value });
|
||||
currentUrl = `/api/qr?${p}`;
|
||||
preview.innerHTML = `<img src="${currentUrl}" alt="QR">`;
|
||||
document.getElementById('btnDownload').disabled = false;
|
||||
document.getElementById('btnCopy').disabled = false;
|
||||
info.textContent = `${p.get('size')}px/模块 · ${p.get('margin')}px边距`;
|
||||
}, 300);
|
||||
}
|
||||
|
||||
textEl.addEventListener('input', update);
|
||||
levelEl.addEventListener('change', update);
|
||||
marginEl.addEventListener('input', update);
|
||||
sizeEl.addEventListener('input', update);
|
||||
|
||||
document.getElementById('btnDownload').onclick = () => {
|
||||
if (currentUrl) { const a = document.createElement('a'); a.href = currentUrl; a.download = 'qrcode.png'; a.click(); }
|
||||
};
|
||||
document.getElementById('btnCopy').onclick = async () => {
|
||||
if (currentUrl) {
|
||||
try { await navigator.clipboard.writeText(location.origin + currentUrl); alert('已复制'); }
|
||||
catch { prompt('复制以下链接:', location.origin + currentUrl); }
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user