This commit is contained in:
2026-05-15 19:36:43 +08:00
parent 659054beb7
commit 085f59eb2b
7 changed files with 705 additions and 1 deletions
+155
View File
@@ -0,0 +1,155 @@
package http
import (
"context"
_ "embed"
"log"
"meshgo/config"
"meshgo/stats"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
// Server HTTP 管理界面服务
type Server struct {
srv *http.Server
enabled bool
}
// New 创建 HTTP 服务(不启动)
func New(cfg *config.AdminConfig) *Server {
if !cfg.Enabled {
return &Server{enabled: false}
}
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
// 预留认证中间件扩展点
r.Use(AuthMiddleware(cfg))
// 路由
admin := r.Group("/admin/mqtt")
{
admin.GET("/api/stats", handleStats)
admin.GET("/api/clients", handleClients)
}
r.GET("/admin/mqtt", serveIndex)
r.GET("/", serveHome)
addr := cfg.Port
if addr == "" {
addr = ":8080"
}
return &Server{
enabled: true,
srv: &http.Server{
Addr: addr,
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
},
}
}
// Start 启动 HTTP 服务(goroutine
func (s *Server) Start() {
if !s.enabled {
return
}
go func() {
addr := s.srv.Addr
log.Printf("[http] 管理界面已启动: http://%s/", addr)
if err := s.srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Printf("[http] 管理界面启动失败: %v", err)
}
}()
}
// Close 优雅关闭
func (s *Server) Close() error {
if !s.enabled {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
return s.srv.Shutdown(ctx)
}
// Enabled 返回是否启用
func (s *Server) Enabled() bool { return s.enabled }
// ---------------------------------------------------------------------------
// 路由处理
// ---------------------------------------------------------------------------
// serveIndex 返回管理页面
func serveIndex(c *gin.Context) {
c.Header("Content-Type", "text/html; charset=utf-8")
c.String(http.StatusOK, indexHTML)
}
// handleStats 返回实时统计(JSON
func handleStats(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": stats.GetStats(),
})
}
// handleClients 返回在线客户端列表(JSON)
func handleClients(c *gin.Context) {
st := stats.GetStats()
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": st.Clients,
})
}
// ---------------------------------------------------------------------------
// 认证中间件(预留扩展点)
// AuthMiddleware 根据 cfg.AuthType 选择对应认证策略
// 当前支持:none
// 预留支持:basic、token
// ---------------------------------------------------------------------------
// AuthMiddleware 认证中间件工厂
func AuthMiddleware(cfg *config.AdminConfig) gin.HandlerFunc {
switch cfg.AuthType {
case "basic":
return basicAuth(cfg.Username, cfg.Password)
case "token":
// TODO: token 认证
return func(c *gin.Context) { c.Next() }
default:
// none:不做认证
return func(c *gin.Context) { c.Next() }
}
}
// basicAuth Basic 认证
func basicAuth(user, pass string) gin.HandlerFunc {
return func(c *gin.Context) {
u, p, ok := c.Request.BasicAuth()
if !ok || u != user || p != pass {
c.Header("WWW-Authenticate", `Basic realm="meshgo"`)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"code": 401,
"msg": "未授权",
})
return
}
c.Next()
}
}
// ---------------------------------------------------------------------------
// 模板(go:embed 内嵌)
// ---------------------------------------------------------------------------
//go:embed index.html
var indexHTML string
+237
View File
@@ -0,0 +1,237 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>meshgo 管理面板</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: #f0f2f5; color: #333; }
header { background: #1677ff; color: #fff; padding: 16px 24px; font-size: 18px; font-weight: 600; }
.container { max-width: 1200px; margin: 24px auto; padding: 0 16px; }
/* 指标卡片 */
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px; }
.card { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
.card .label { font-size: 13px; color: #888; margin-bottom: 6px; }
.card .value { font-size: 28px; font-weight: 700; color: #1677ff; }
.card .sub { font-size: 12px; color: #aaa; margin-top: 4px; }
/* 图表区 */
.charts { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 24px; }
.chart-box { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
.chart-box h3 { font-size: 15px; color: #333; margin-bottom: 16px; }
.chart-wrap { position: relative; height: 220px; }
/* 客户端表格 */
.table-box { background: #fff; border-radius: 8px; padding: 20px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
.table-box h3 { font-size: 15px; color: #333; margin-bottom: 16px; }
table { width: 100%; border-collapse: collapse; }
th { text-align: left; padding: 10px 12px; background: #fafafa; border-bottom: 1px solid #eee; font-size: 13px; color: #666; }
td { padding: 10px 12px; border-bottom: 1px solid #f0f0f0; font-size: 13px; }
tr:hover td { background: #fafafa; }
.online-dot { display: inline-block; width: 8px; height: 8px; background: #52c41a; border-radius: 50%; margin-right: 6px; }
.tag { display: inline-block; padding: 2px 8px; background: #e6f4ff; color: #1677ff; border-radius: 4px; font-size: 12px; margin: 1px; }
.refresh-info { font-size: 12px; color: #aaa; text-align: right; margin-top: 8px; }
</style>
</head>
<body>
<header>meshgo MQTT 管理面板</header>
<div class="container">
<!-- 指标卡片 -->
<div class="cards">
<div class="card">
<div class="label">当前连接</div>
<div class="value" id="connections">-</div>
<div class="sub">实时在线客户端数</div>
</div>
<div class="card">
<div class="label">累计消息</div>
<div class="value" id="messages_total">-</div>
<div class="sub">所有主题消息总数</div>
</div>
<div class="card">
<div class="label">msh/# 消息</div>
<div class="value" id="messages_msh">-</div>
<div class="sub">mesh 主题消息数</div>
</div>
<div class="card">
<div class="label">运行时长</div>
<div class="value" id="uptime">-</div>
<div class="sub" id="uptime_sub">-</div>
</div>
</div>
<!-- 图表 -->
<div class="charts">
<div class="chart-box">
<h3>消息趋势(最近 30 条)</h3>
<div class="chart-wrap"><canvas id="trendChart"></canvas></div>
</div>
<div class="chart-box">
<h3>主题分布</h3>
<div class="chart-wrap"><canvas id="topicChart"></canvas></div>
</div>
</div>
<!-- 在线客户端 -->
<div class="table-box">
<h3>在线客户端 <span id="client_count" style="font-weight:normal;font-size:13px;color:#888"></span></h3>
<table>
<thead>
<tr>
<th>状态</th>
<th>客户端 ID</th>
<th>IP 地址</th>
<th>用户名</th>
<th>订阅数</th>
<th>连接时间</th>
</tr>
</thead>
<tbody id="clients_tbody">
<tr><td colspan="6" style="text-align:center;color:#aaa;padding:24px">暂无数据</td></tr>
</tbody>
</table>
<div class="refresh-info">每 3 秒自动刷新</div>
</div>
</div>
<script>
// ---------------------------------------------------------------------------
// 消息趋势环形缓冲
// ---------------------------------------------------------------------------
const MAX_TREND = 30;
const trendBuffer = [];
let trendLabels = [];
let trendData = [];
const trendCtx = document.getElementById('trendChart').getContext('2d');
const trendChart = new Chart(trendCtx, {
type: 'line',
data: {
labels: trendLabels,
datasets: [{
label: '消息数',
data: trendData,
borderColor: '#1677ff',
backgroundColor: 'rgba(22,119,255,0.1)',
fill: true,
tension: 0.3,
pointRadius: 3,
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
scales: {
x: { display: false },
y: { beginAtZero: true, ticks: { stepSize: 1 } }
},
plugins: { legend: { display: false } }
}
});
const topicCtx = document.getElementById('topicChart').getContext('2d');
const topicChart = new Chart(topicCtx, {
type: 'bar',
data: { labels: [], datasets: [{ label: '消息数', data: [], backgroundColor: '#1677ff' }] },
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
plugins: { legend: { display: false } },
scales: {
x: { ticks: { maxRotation: 45, minRotation: 45, font: { size: 11 } } },
y: { beginAtZero: true }
}
}
});
let lastTotal = 0;
function formatUptime(s) {
if (s < 60) return s + ' 秒';
if (s < 3600) return Math.floor(s/60) + ' 分 ' + (s%60) + ' 秒';
const h = Math.floor(s/3600);
const m = Math.floor((s%3600)/60);
const sec = s%60;
return h + ' 小时 ' + m + ' 分 ' + sec + ' 秒';
}
function fetchStats() {
fetch('/admin/mqtt/api/stats')
.then(r => r.json())
.then(res => {
const d = res.data;
// 指标卡片
document.getElementById('connections').textContent = d.connections;
document.getElementById('messages_total').textContent = d.messages_total;
document.getElementById('messages_msh').textContent = d.messages_msh;
document.getElementById('uptime').textContent = formatUptime(d.uptime);
document.getElementById('uptime_sub').textContent = '服务已运行 ' + formatUptime(d.uptime);
// 趋势图(增量)
const delta = d.messages_total - lastTotal;
lastTotal = d.messages_total;
trendBuffer.push(delta);
if (trendBuffer.length > MAX_TREND) trendBuffer.shift();
const now = new Date();
trendLabels.length = 0;
trendLabels.push(...trendBuffer.map((_, i) => ''));
trendData.length = 0;
trendData.push(...trendBuffer);
trendChart.data.labels = trendLabels;
trendChart.data.datasets[0].data = trendData;
trendChart.update();
// 主题分布
const topics = d.topics || {};
const sorted = Object.entries(topics).sort((a, b) => b[1] - a[1]).slice(0, 10);
topicChart.data.labels = sorted.map(x => x[0]);
topicChart.data.datasets[0].data = sorted.map(x => x[1]);
topicChart.update();
// 客户端表格
document.getElementById('client_count').textContent = '(' + d.clients.length + ')';
const tbody = document.getElementById('clients_tbody');
if (!d.clients || d.clients.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;color:#aaa;padding:24px">暂无在线客户端</td></tr>';
} else {
tbody.innerHTML = d.clients.map(c => {
const subs = c.subs_count > 0
? Array(Math.min(c.subs_count, 5)).fill('<span class="tag">...</span>').join('')
: '-';
const time = new Date(c.connected_at).toLocaleString('zh-CN', { hour12: false });
return `<tr>
<td><span class="online-dot"></span>在线</td>
<td>${esc(c.id)}</td>
<td>${esc(c.remote_addr)}</td>
<td>${esc(c.username)}</td>
<td>${c.subs_count}</td>
<td>${time}</td>
</tr>`;
}).join('');
}
})
.catch(() => {});
}
function esc(s) {
if (!s) return '';
return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
}
// 每 3 秒刷新
fetchStats();
setInterval(fetchStats, 3000);
</script>
</body>
</html>