Initial commit: Modular personal toolbox with high-fidelity Chinese stroke order tool and CI/CD
Build and Push Docker Image / build (push) Successful in 2m42s

This commit is contained in:
2026-02-23 02:04:11 -08:00
commit 109a4d0df0
21 changed files with 1182 additions and 0 deletions
+119
View File
@@ -0,0 +1,119 @@
package main
import (
"bytes"
"embed"
"flag"
"io/fs"
"log"
"net/http"
"os"
"strconv"
"toolbox/pkg/base"
_ "toolbox/pkg/zitie" // 匿名导入以触发 init()
"github.com/gin-gonic/gin"
)
//go:embed web/*
var webFS embed.FS
func main() {
// 定义参数
portFlag := flag.Int("port", 0, "端口号 (优先于环境变量 PORT)")
gaFlag := flag.String("ga", "", "Google Analytics ID (例如: G-XXXXXXXXXX)")
flag.Parse()
// 环境变量支持
gaID := *gaFlag
if gaID == "" {
gaID = os.Getenv("GA_ID")
}
if os.Getenv("GIN_MODE") == "release" {
gin.SetMode(gin.ReleaseMode)
}
r := gin.New()
r.Use(gin.Logger(), gin.Recovery())
r.RedirectTrailingSlash = false
r.RedirectFixedPath = false
_ = r.SetTrustedProxies(nil)
// 1. 自动发现并注册工具路由
api := r.Group("/api")
{
for id, tool := range base.Registry {
if err := tool.Init(); err != nil {
log.Fatalf("Failed to initialize tool %s: %v", id, err)
}
tool.RegisterRoutes(api.Group("/" + id))
}
}
// 2. 静态资源与页面
subFS, _ := fs.Sub(webFS, "web")
r.StaticFS("/static", http.FS(subFS))
r.GET("/", func(c *gin.Context) {
content, err := webFS.ReadFile("web/index.html")
if err != nil {
c.String(http.StatusNotFound, "index.html not found")
return
}
// 动态注入 Google Analytics (遵循官方最新规范)
if gaID != "" {
gaScript := `
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=` + gaID + `"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '` + gaID + `');
</script>`
content = bytes.Replace(content, []byte("</head>"), []byte(gaScript+"</head>"), 1)
}
c.Data(http.StatusOK, "text/html; charset=utf-8", content)
})
// 3. 工具列表发现接口
r.GET("/api/tools", func(c *gin.Context) {
var list []map[string]string
for _, t := range base.Registry {
list = append(list, map[string]string{
"id": t.ID(),
"name": t.Name(),
"desc": t.Description(),
})
}
c.JSON(http.StatusOK, list)
})
// 4. 全路径回退 (SPA Routing)
r.NoRoute(func(c *gin.Context) {
content, err := webFS.ReadFile("web/index.html")
if err != nil {
c.String(http.StatusNotFound, "index.html not found")
return
}
c.Data(http.StatusOK, "text/html; charset=utf-8", content)
})
// 5. 确定最终使用的端口
var finalPort string
if *portFlag > 0 {
finalPort = strconv.Itoa(*portFlag)
} else if envPort := os.Getenv("PORT"); envPort != "" {
finalPort = envPort
} else {
finalPort = "8080"
}
log.Printf("Toolbox server starting on :%s", finalPort)
if err := r.Run(":" + finalPort); err != nil {
log.Fatalf("Server failed: %v", err)
}
}
+167
View File
@@ -0,0 +1,167 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Own-Tools | 个人工具箱</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🖋️</text></svg>">
<style>
:root { --sidebar-width: 260px; --apple-bg: #f5f5f7; --apple-blue: #0071e3; --sidebar-bg: rgba(255, 255, 255, 0.9); }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; background-color: var(--apple-bg); color: #1d1d1f; display: flex; height: 100vh; width: 100vw; overflow: hidden; }
.sidebar { width: var(--sidebar-width); min-width: var(--sidebar-width); background: var(--sidebar-bg); backdrop-filter: blur(20px); border-right: 1px solid #d2d2d7; display: flex; flex-direction: column; padding: 24px 0; z-index: 100; }
.sidebar-header { padding: 0 24px 24px; border-bottom: 1px solid #e5e5e7; margin-bottom: 16px; }
.sidebar-header h2 { font-size: 22px; font-weight: 700; margin: 0; color: #1d1d1f; letter-spacing: -0.5px; cursor: pointer; }
.nav-list { flex: 1; overflow-y: auto; }
.nav-item { padding: 12px 24px; cursor: pointer; transition: all 0.2s; font-size: 15px; font-weight: 500; color: #424245; display: flex; align-items: center; gap: 12px; }
.nav-item:hover { background: rgba(0,0,0,0.04); color: #000; }
.nav-item.active { background: var(--apple-blue); color: #ffffff; }
.main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; padding: 40px 60px; }
.tool-panel { display: none; animation: fadeIn 0.3s ease-out; }
.tool-panel.active { display: block; }
@keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
.tabs-container { display: flex; gap: 10px; border-bottom: 1px solid #d2d2d7; margin-bottom: 24px; overflow-x: auto; }
.tab-btn { padding: 10px 20px; cursor: pointer; font-size: 16px; font-weight: 600; color: #86868b; border-bottom: 3px solid transparent; transition: all 0.2s; }
.tab-btn.active { color: var(--apple-blue); border-bottom-color: var(--apple-blue); }
.card { background: white; border-radius: 18px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.04); margin-bottom: 30px; border: 1px solid rgba(0,0,0,0.05); }
textarea { padding: 14px 18px; border: 1px solid #d2d2d7; border-radius: 12px; font-size: 17px; background-color: #fbfbfd; width: 100%; box-sizing: border-box; min-height: 150px; font-family: inherit; resize: vertical; }
.input-row-bottom { display: flex; gap: 20px; align-items: flex-end; margin-top: 20px; }
.input-group { display: flex; flex-direction: column; gap: 8px; }
select { padding: 13px 18px; border: 1px solid #d2d2d7; border-radius: 12px; font-size: 16px; background-color: #fbfbfd; cursor: pointer; }
button { background-color: var(--apple-blue); color: white; border: none; padding: 0 30px; border-radius: 12px; font-size: 16px; font-weight: 600; cursor: pointer; height: 48px; transition: all 0.2s; }
#pdf-preview-container { width: 100%; height: 850px; border-radius: 20px; overflow: hidden; box-shadow: 0 10px 40px rgba(0,0,0,0.1); background: #fff; border: 1px solid #d2d2d7; }
iframe { width: 100%; height: 100%; border: none; }
</style>
</head>
<body>
<div class="sidebar">
<div class="sidebar-header" onclick="navigateTo('/')"><h2>Own-Tools</h2></div>
<div id="nav-list" class="nav-list">
<div id="nav-welcome" class="nav-item active" onclick="navigateTo('/')"><span>🏠</span> 仪表盘</div>
</div>
</div>
<div class="main-content">
<div id="panel-zitie" class="tool-panel">
<h1 style="font-size: 34px; font-weight: 700; margin-bottom: 20px;">汉字字帖生成器</h1>
<div class="tabs-container">
<div id="tab-teaching" class="tab-btn active" onclick="switchZitieTab('teaching')">2x3 教学方格</div>
<div id="tab-step" class="tab-btn" onclick="switchZitieTab('step')">步进式分解</div>
<div id="tab-manuscript" class="tab-btn" onclick="switchZitieTab('manuscript')">古风竖排</div>
</div>
<div class="card">
<div class="form-layout">
<label id="input-label">输入汉字内容 (标点符号将被自动过滤)</label>
<textarea id="chars" placeholder="输入内容...">永和九年,岁在癸丑。
暮春之初,会于会稽山阴之兰亭,修禊事也。</textarea>
<div class="input-row-bottom">
<div class="input-group">
<label>纸张大小</label>
<select id="paper_size" style="width: 180px;">
<option value="A4">A4 (210x297mm)</option>
<option value="Letter">Letter (8.5x11in)</option>
</select>
</div>
<div id="font-select-group" class="input-group" style="display: none;">
<label>书法字体</label>
<select id="font_type" style="width: 180px;">
<option value="kaiti">华光楷体</option>
<option value="xingshu">华光行草</option>
<option value="lishu">华光隶变</option>
<option value="songti">华光书宋</option>
</select>
</div>
<div style="flex: 1;"></div>
<button onclick="generatePDF()">生成高清预览</button>
</div>
</div>
</div>
<div id="pdf-preview-container" style="display:none;"><iframe id="pdf-frame"></iframe></div>
</div>
<div id="panel-welcome" class="tool-panel active">
<h1 style="font-size: 40px; font-weight: 700;">欢迎使用</h1>
<p style="font-size: 20px; color: #86868b;">请选择工具开始工作。</p>
<div style="margin-top: 40px; display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
<div class="card" style="cursor:pointer;" onclick="navigateTo('/zitie')">
<h3>🖋️ 汉字字帖</h3>
<p>生成高颜值的硬笔/毛笔书法练习帖。</p>
</div>
</div>
</div>
</div>
<script>
let currentMode = 'teaching';
async function loadTools() {
try {
const response = await fetch('/api/tools');
const tools = await response.json();
const navList = document.getElementById('nav-list');
tools.forEach(tool => {
const item = document.createElement('div');
item.className = 'nav-item'; item.id = `nav-${tool.id}`;
item.innerHTML = `<span>🛠️</span> ${tool.name}`;
item.onclick = () => navigateTo(`/${tool.id}`);
navList.appendChild(item);
});
renderCurrentPath();
} catch (e) { console.error(e); }
}
function navigateTo(path) {
window.history.pushState({}, '', path);
renderCurrentPath();
}
function renderCurrentPath() {
const path = window.location.pathname.replace('/', '') || 'welcome';
document.querySelectorAll('.tool-panel').forEach(p => p.classList.remove('active'));
const target = document.getElementById(`panel-${path}`);
if (target) target.classList.add('active');
document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
const activeNav = document.getElementById(`nav-${path}`);
if (activeNav) activeNav.classList.add('active');
}
window.onpopstate = renderCurrentPath;
function switchZitieTab(mode) {
currentMode = mode;
document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
document.getElementById(`tab-${mode}`).classList.add('active');
document.getElementById('font-select-group').style.display = (mode === 'manuscript') ? 'flex' : 'none';
const labels = {
'teaching': '输入汉字内容 (2x3 教学方格模式下标点将被自动过滤)',
'step': '输入汉字内容 (步进式分解模式下标点将被自动过滤)',
'manuscript': '输入汉字内容 (古风竖排支持换行,标点将被过滤)'
};
document.getElementById('input-label').innerText = labels[mode];
}
async function generatePDF() {
const chars = document.getElementById('chars').value;
const paper_size = document.getElementById('paper_size').value;
const font_type = document.getElementById('font_type').value;
const btn = document.querySelector('button');
btn.innerText = '正在绘制矢量图...'; btn.disabled = true;
try {
const response = await fetch(`/api/zitie/${currentMode}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chars, paper_size, font_type })
});
if (response.ok) {
const blob = await response.blob();
document.getElementById('pdf-preview-container').style.display = 'block';
document.getElementById('pdf-frame').src = URL.createObjectURL(blob);
} else { alert('生成失败'); }
} catch (e) { alert('网络错误'); } finally { btn.innerText = '生成高清预览'; btn.disabled = false; }
}
loadTools();
</script>
</body>
</html>