This commit is contained in:
2025-08-24 13:01:09 +08:00
parent 61e51ad014
commit f028913eb8
36 changed files with 10420 additions and 70 deletions

View File

@@ -0,0 +1,101 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Go Web服务器</title>
<link rel="stylesheet" href="/static/style.css">
</head>
<body>
<div class="container">
<header>
<h1>🚀 Go Web服务器</h1>
<p>一个使用Go语言编写的简单HTTP服务器示例</p>
</header>
<main>
<section class="api-section">
<h2>📚 API接口测试</h2>
<div class="api-group">
<h3>用户管理</h3>
<div class="api-item">
<button onclick="getUsers()">获取所有用户</button>
<span class="method get">GET</span>
<span class="endpoint">/api/users</span>
</div>
<div class="api-item">
<button onclick="createUser()">创建用户</button>
<span class="method post">POST</span>
<span class="endpoint">/api/users</span>
</div>
<div class="api-item">
<input type="number" id="userId" placeholder="用户ID" min="1">
<button onclick="getUser()">获取用户</button>
<span class="method get">GET</span>
<span class="endpoint">/api/users/{id}</span>
</div>
<div class="api-item">
<button onclick="deleteUser()">删除用户</button>
<span class="method delete">DELETE</span>
<span class="endpoint">/api/users/{id}</span>
</div>
</div>
<div class="api-group">
<h3>系统信息</h3>
<div class="api-item">
<button onclick="getHealth()">健康检查</button>
<span class="method get">GET</span>
<span class="endpoint">/health</span>
</div>
<div class="api-item">
<button onclick="getStats()">服务器统计</button>
<span class="method get">GET</span>
<span class="endpoint">/api/stats</span>
</div>
</div>
</section>
<section class="form-section">
<h2>📝 创建用户表单</h2>
<form id="userForm">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="number" id="age" name="age" min="0" max="150" required>
</div>
<button type="submit">创建用户</button>
</form>
</section>
<section class="response-section">
<h2>📄 响应结果</h2>
<pre id="response"></pre>
</section>
</main>
<footer>
<p>&copy; 2024 Go Web服务器示例项目</p>
</footer>
</div>
<script src="/static/script.js"></script>
</body>
</html>

View File

@@ -0,0 +1,241 @@
// script.js - JavaScript 文件
// API 基础URL
const API_BASE = '/api';
// 响应显示元素
const responseElement = document.getElementById('response');
// 显示响应结果
function showResponse(data, isError = false) {
responseElement.textContent = JSON.stringify(data, null, 2);
responseElement.className = isError ? 'error' : 'success';
}
// 显示加载状态
function showLoading() {
responseElement.textContent = '加载中...';
responseElement.className = 'loading';
}
// API 请求封装
async function apiRequest(url, options = {}) {
try {
showLoading();
const response = await fetch(url, {
headers: {
'Content-Type': 'application/json',
...options.headers
},
...options
});
const data = await response.json();
if (!response.ok) {
showResponse(data, true);
return null;
}
showResponse(data);
return data;
} catch (error) {
showResponse({
error: '网络请求失败',
message: error.message
}, true);
return null;
}
}
// 获取所有用户
async function getUsers() {
await apiRequest(`${API_BASE}/users`);
}
// 获取指定用户
async function getUser() {
const userId = document.getElementById('userId').value;
if (!userId) {
showResponse({
error: '请输入用户ID'
}, true);
return;
}
await apiRequest(`${API_BASE}/users/${userId}`);
}
// 创建用户(使用按钮)
async function createUser() {
const userData = {
name: '测试用户',
email: `test${Date.now()}@example.com`,
age: Math.floor(Math.random() * 50) + 18
};
await apiRequest(`${API_BASE}/users`, {
method: 'POST',
body: JSON.stringify(userData)
});
}
// 删除用户
async function deleteUser() {
const userId = document.getElementById('userId').value;
if (!userId) {
showResponse({
error: '请输入用户ID'
}, true);
return;
}
if (!confirm(`确定要删除用户 ${userId} 吗?`)) {
return;
}
await apiRequest(`${API_BASE}/users/${userId}`, {
method: 'DELETE'
});
}
// 健康检查
async function getHealth() {
await apiRequest('/health');
}
// 获取服务器统计
async function getStats() {
await apiRequest(`${API_BASE}/stats`);
}
// 表单提交处理
document.getElementById('userForm').addEventListener('submit', async function(e) {
e.preventDefault();
const formData = new FormData(this);
const userData = {
name: formData.get('name'),
email: formData.get('email'),
age: parseInt(formData.get('age'))
};
// 验证数据
if (!userData.name || !userData.email || !userData.age) {
showResponse({
error: '请填写所有必填字段'
}, true);
return;
}
if (userData.age < 0 || userData.age > 150) {
showResponse({
error: '年龄必须在0-150之间'
}, true);
return;
}
const result = await apiRequest(`${API_BASE}/users`, {
method: 'POST',
body: JSON.stringify(userData)
});
if (result) {
// 清空表单
this.reset();
}
});
// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', function() {
// 显示欢迎信息
showResponse({
message: '欢迎使用 Go Web服务器 API 测试页面!',
instructions: [
'点击上方按钮测试各种API接口',
'使用表单创建新用户',
'查看下方的响应结果'
]
});
// 自动获取用户列表
setTimeout(getUsers, 1000);
});
// 键盘快捷键
document.addEventListener('keydown', function(e) {
// Ctrl + Enter 快速创建用户
if (e.ctrlKey && e.key === 'Enter') {
createUser();
}
// Ctrl + R 刷新用户列表
if (e.ctrlKey && e.key === 'r') {
e.preventDefault();
getUsers();
}
});
// 工具函数:格式化时间
function formatTime(timestamp) {
return new Date(timestamp).toLocaleString('zh-CN');
}
// 工具函数:格式化文件大小
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
// 工具函数:复制到剪贴板
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
console.log('已复制到剪贴板');
} catch (err) {
console.error('复制失败:', err);
}
}
// 添加复制响应结果的功能
responseElement.addEventListener('click', function() {
if (this.textContent && this.textContent !== '加载中...') {
copyToClipboard(this.textContent);
}
});
// 自动刷新功能(可选)
let autoRefresh = false;
let refreshInterval;
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
if (autoRefresh) {
refreshInterval = setInterval(getUsers, 5000);
console.log('自动刷新已启用');
} else {
clearInterval(refreshInterval);
console.log('自动刷新已禁用');
}
}
// 错误重试机制
async function retryRequest(requestFunc, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await requestFunc();
} catch (error) {
if (i === maxRetries - 1) {
throw error;
}
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}

View File

@@ -0,0 +1,271 @@
/* style.css - 样式文件 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #333;
background-color: #f5f5f5;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 40px;
padding: 30px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
header h1 {
font-size: 2.5em;
margin-bottom: 10px;
}
header p {
font-size: 1.2em;
opacity: 0.9;
}
main {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 30px;
margin-bottom: 40px;
}
section {
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.response-section {
grid-column: 1 / -1;
}
h2 {
color: #333;
margin-bottom: 20px;
font-size: 1.5em;
border-bottom: 2px solid #667eea;
padding-bottom: 10px;
}
h3 {
color: #555;
margin: 20px 0 15px 0;
font-size: 1.2em;
}
.api-group {
margin-bottom: 30px;
}
.api-item {
display: flex;
align-items: center;
gap: 15px;
margin-bottom: 15px;
padding: 15px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #667eea;
}
.api-item button {
background: #667eea;
color: white;
border: none;
padding: 8px 16px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
min-width: 120px;
}
.api-item button:hover {
background: #5a6fd8;
}
.api-item input {
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
width: 100px;
}
.method {
font-weight: bold;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
text-transform: uppercase;
min-width: 60px;
text-align: center;
}
.method.get {
background: #28a745;
color: white;
}
.method.post {
background: #007bff;
color: white;
}
.method.delete {
background: #dc3545;
color: white;
}
.endpoint {
font-family: 'Courier New', monospace;
background: #e9ecef;
padding: 4px 8px;
border-radius: 4px;
font-size: 13px;
color: #495057;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: 500;
color: #555;
}
.form-group input {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
transition: border-color 0.3s;
}
.form-group input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}
#userForm button {
background: #28a745;
color: white;
border: none;
padding: 12px 30px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s;
width: 100%;
}
#userForm button:hover {
background: #218838;
}
#response {
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 5px;
padding: 20px;
font-family: 'Courier New', monospace;
font-size: 14px;
line-height: 1.4;
white-space: pre-wrap;
word-wrap: break-word;
max-height: 400px;
overflow-y: auto;
color: #495057;
}
footer {
text-align: center;
padding: 20px;
color: #666;
border-top: 1px solid #eee;
margin-top: 40px;
}
/* 响应式设计 */
@media (max-width: 768px) {
main {
grid-template-columns: 1fr;
gap: 20px;
}
.api-item {
flex-direction: column;
align-items: flex-start;
gap: 10px;
}
.api-item button {
width: 100%;
}
header h1 {
font-size: 2em;
}
.container {
padding: 10px;
}
}
/* 加载动画 */
.loading {
opacity: 0.6;
pointer-events: none;
}
.loading::after {
content: '';
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
margin: -10px 0 0 -10px;
border: 2px solid #667eea;
border-radius: 50%;
border-top-color: transparent;
animation: spin 1s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* 成功和错误状态 */
.success {
color: #28a745;
}
.error {
color: #dc3545;
}