random-api-go/public/index.html
wood chen 260bddb56b refactor(public): improve metrics loading and display logic
- Updated the metrics API endpoint from '/metrics' to '/api/metrics' for better organization.
- Added data validation to ensure the metrics data received is an object, enhancing error handling.
- Refactored the updateMetricsDisplay function to dynamically create metric items, improving the display of metrics.
- Implemented HTML escaping for metric keys and values to prevent XSS vulnerabilities.
- Cleared existing content in the metrics container before updating, ensuring a clean display.
2024-12-01 01:49:50 +08:00

272 lines
10 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="zh-cmn-Hans">
<head>
<title>随机文件api</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="随机图API, 随机视频等 ">
<link rel="shortcut icon" size="32x32" href="https://i.czl.net/r2/2023/06/20/649168ebc2b5d.png">
<link rel="stylesheet" href="https://i.czl.net/g-f/frame/czlfonts/slice/font.css" media="all">
<link rel="stylesheet" href="https://i.czl.net/g-f/frame/prose.css" media="all">
<link rel="stylesheet" href="./css/main.css" media="all">
<style>
</style>
<script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/markdown-it/12.3.2/markdown-it.min.js"></script>
<script defer src="https://analytics.czl.net/script.js"
data-website-id="67f71dbc-799c-46b6-9c23-b1b012daef65"></script>
</head>
<body>
<div class="overlay">
<main>
<div id="system-metrics"></div>
<div id="markdown-content" class="prose prose-dark">
</div>
</main>
</div>
<!-- 渲染markdown -->
<script>
// 创建带有配置的 markdown-it 实例
var md = window.markdownit({
html: true
});
// 用于存储配置的全局变量
let cachedEndpointConfig = null;
// 加载配置的函数
async function loadEndpointConfig() {
if (cachedEndpointConfig) {
return cachedEndpointConfig;
}
try {
const response = await fetch('/config/endpoint.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
cachedEndpointConfig = await response.json();
return cachedEndpointConfig;
} catch (error) {
console.error('加载endpoint配置失败:', error);
return {};
}
}
// 加载统计数据
async function loadStats() {
try {
const [statsResponse, urlStatsResponse, endpointConfig] = await Promise.all([
fetch('/stats'),
fetch('/urlstats'),
loadEndpointConfig()
]);
const stats = await statsResponse.json();
const urlStats = await urlStatsResponse.json();
// 只显示 endpoint.json 中配置的路径
const filteredPaths = {};
for (const [category, types] of Object.entries(endpointConfig)) {
if (urlStats.paths[category]) {
filteredPaths[category] = {};
for (const [type, desc] of Object.entries(types)) {
if (urlStats.paths[category][type]) {
filteredPaths[category][type] = {
path: urlStats.paths[category][type],
description: desc
};
}
}
}
}
await updateStats(stats, filteredPaths);
} catch (error) {
console.error('Error loading stats:', error);
}
}
// 更新统计显示
async function updateStats(stats, paths) {
const startDate = new Date('2024-11-1');
const today = new Date();
const daysSinceStart = Math.ceil((today - startDate) / (1000 * 60 * 60 * 24));
let totalCalls = 0;
let todayCalls = 0;
// 计算总调用次数
Object.entries(stats).forEach(([endpoint, stat]) => {
totalCalls += stat.total_calls;
todayCalls += stat.today_calls;
});
const avgCallsPerDay = Math.round(totalCalls / daysSinceStart);
// 更新总览统计
const summaryHtml = `
<div class="stats-summary">
<div class="stats-header">
<h2>📊 接口调用次数 <span class="refresh-icon">🔄</span></h2>
</div>
<div class="stats-grid">
<div class="stats-item">今日总调用:${todayCalls} 次</div>
<div class="stats-item">平均每天调用:${avgCallsPerDay} 次</div>
<div class="stats-item">总调用次数:${totalCalls} 次</div>
<div class="stats-item">统计开始日期2024-11-1</div>
</div>
</div>
`;
// 获取 endpoint 配置
const endpointConfig = await loadEndpointConfig();
// 生成详细统计表格
let detailHtml = `
<table>
<thead>
<tr>
<th>接口名称</th>
<th>今日调用</th>
<th>总调用</th>
<th>URL数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
`;
// 按 order 排序并生成表格行
const endpoints = Object.entries(endpointConfig)
.sort(([, a], [, b]) => a.order - b.order);
for (const [endpoint, config] of endpoints) {
const stat = stats[endpoint] || { today_calls: 0, total_calls: 0 };
const urlCount = urlStats[endpoint]?.total_urls || 0;
detailHtml += `
<tr>
<td>
<a href="javascript:void(0)"
onclick="copyToClipboard('${endpoint}')"
class="endpoint-link"
title="点击复制链接">
${config.name}
</a>
</td>
<td>${stat.today_calls}</td>
<td>${stat.total_calls}</td>
<td>${urlCount}</td>
<td>
<a href="/${endpoint}" target="_blank" rel="noopener noreferrer" title="测试接口">👀</a>
<a href="javascript:void(0)" onclick="copyToClipboard('${endpoint}')" title="复制链接">📋</a>
</td>
</tr>
`;
}
detailHtml += `
</tbody>
</table>
`;
// 更新 DOM
const summaryElement = document.getElementById('stats-summary');
const detailElement = document.getElementById('stats-detail');
if (summaryElement) summaryElement.innerHTML = summaryHtml;
if (detailElement) detailElement.innerHTML = detailHtml;
}
// 复制链接功能
function copyToClipboard(endpoint) {
const url = `${window.location.protocol}//${window.location.host}/${endpoint}`;
navigator.clipboard.writeText(url).then(() => {
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = '链接已复制到剪贴板!';
document.body.appendChild(toast);
setTimeout(() => toast.remove(), 2000);
}).catch(err => {
console.error('复制失败:', err);
});
}
// 先加载 markdown 内容
fetch('./index.md')
.then(response => response.text())
.then(markdownText => {
document.getElementById('markdown-content').innerHTML = md.render(markdownText);
// markdown 加载完成后等待一小段时间再加载统计数据
setTimeout(loadStats, 100);
})
.catch(error => console.error('Error loading index.md:', error));
// 定期更新统计数据
setInterval(loadStats, 5 * 1000);
async function loadMetrics() {
try {
const response = await fetch('/api/metrics');
const data = await response.json();
// 添加数据验证
if (!data || typeof data !== 'object') {
throw new Error('Invalid metrics data received');
}
updateMetricsDisplay(data);
} catch (error) {
console.error('Error loading metrics:', error);
document.getElementById('metrics-container').innerHTML =
'<p class="error">加载指标数据时出错,请稍后重试</p>';
}
}
function updateMetricsDisplay(metricsData) {
// 确保 metricsData 是有效对象
if (!metricsData || typeof metricsData !== 'object') {
console.error('Invalid metrics data');
return;
}
const container = document.getElementById('metrics-container');
container.innerHTML = ''; // 清空现有内容
// 使用 Object.entries 之前进行安全检查
const entries = Object.entries(metricsData).filter(([key, value]) => key && value !== undefined);
entries.forEach(([key, value]) => {
const metricDiv = document.createElement('div');
metricDiv.className = 'metric-item';
metricDiv.innerHTML = `
<h3>${escapeHtml(key)}</h3>
<p>${escapeHtml(String(value))}</p>
`;
container.appendChild(metricDiv);
});
}
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&#039;");
}
// 定期更新监控数据
setInterval(loadMetrics, 5000);
// 初始加载
document.addEventListener('DOMContentLoaded', () => {
loadMetrics();
});
</script>
</body>
</html>