// 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))); } } }