去提问»
提问背景 Question:
接下来,我们要做后台管理ai数据的问题了。通过ai内容的保存表。来进行管理,可以删除,修改状态等,要支持分页。不要再搞什么css外部依赖了。后台是黑色背景。数据要能分页,这前的baike.go不知道你能不能回忆起来。路由可以添加的。

Go+HTML 黑色主题 AI 内容管理后台

发布时间:2026-08-20 01:05 👁️ 阅读:1

为了彻底解决您之前提到的**“分页按钮多了一直往后拉伸、不自动换行”以及“不要外部 CSS 依赖”**的问题,我为您设计了一套纯原生 HTML/CSS(黑色深色主题)加 Go 语言后端的完整管理系统方案。

我们在分页容器中使用了 flex-wrap: wrap;gap 属性,这样无论有多少页,按钮都会在屏幕边缘自动优雅地折行,绝不溢出拉伸。

1. 后端 Go 代码实现 (baike.go 扩展)

这里使用 Go 标准库 net/httphtml/template 实现。我们模拟了一个 AI 内容数据集,并提供了列表分页删除数据切换状态三个路由接口。

package main

import (
	"encoding/json"
	"html/template"
	"log"
	"math"
	"net/http"
	"strconv"
	"sync"
	"time"
)

// AIContent 实体结构
type AIContent struct {
	ID        int    `json:"id"`
	Title     string `json:"title"`
	Prompt    string `json:"prompt"`
	Response  string `json:"response"`
	Status    int    `json:"status"` // 1: 启用, 0: 禁用
	CreatedAt string `json:"created_at"`
}

// 模拟数据库数据
var (
	contentList []AIContent
	mu          sync.Mutex
)

func init() {
	// 初始化35条测试数据,方便测试分页效果
	for i := 1; i <= 35; i++ {
		contentList = append(contentList, AIContent{
			ID:        i,
			Title:     "AI 生成词条 - " + strconv.Itoa(i),
			Prompt:    "帮我写一篇关于第 " + strconv.Itoa(i) + " 个词条的科普。",
			Response:  "这是关于第 " + strconv.Itoa(i) + " 个词条的详细AI解答内容...",
			Status:    1,
			CreatedAt: time.Now().Add(time.Duration(-i) * time.Hour).Format("2006-01-02 15:04"),
		})
	}
}

func main() {
	// 1. 列表页面路由
	http.HandleFunc("/admin/ai/list", handleList)
	// 2. 切换状态 API
	http.HandleFunc("/admin/ai/toggle", handleToggleStatus)
	// 3. 删除 API
	http.HandleFunc("/admin/ai/delete", handleDelete)

	log.Println("管理后台启动成功,监听端口 :8080 ...")
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 列表数据分页处理
func handleList(w http.ResponseWriter, r *http.Request) {
	mu.Lock()
	defer mu.Unlock()

	// 获取分页参数
	pageStr := r.URL.Query().Get("page")
	limitStr := r.URL.Query().Get("limit")

	page, _ := strconv.Atoi(pageStr)
	if page < 1 { page = 1 }
	limit, _ := strconv.Atoi(limitStr)
	if limit < 1 { limit = 8 } // 每页8条

	total := len(contentList)
	totalPages := int(math.Ceil(float64(total) / float64(limit)))
	if page > totalPages && totalPages > 0 { page = totalPages }

	start := (page - 1) * limit
	end := start + limit
	if end > total { end = total }

	var pagedData []AIContent
	if start < total {
		pagedData = contentList[start:end]
	}

	// 生成页码切片(供前端渲染)
	var pages []int
	for i := 1; i <= totalPages; i++ {
		pages = append(pages, i)
	}

	data := map[string]interface{}{
		"List":        pagedData,
		"CurrentPage": page,
		"TotalPages":  totalPages,
		"Pages":       pages,
		"TotalCount":  total,
	}

	tmpl := template.Must(template.New("admin").Parse(htmlTemplate))
	tmpl.Execute(w, data)
}

// 切换状态处理器
func handleToggleStatus(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	mu.Lock()
	defer mu.Unlock()

	id, _ := strconv.Atoi(r.FormValue("id"))
	for i, v := range contentList {
		if v.ID == id {
			if contentList[i].Status == 1 {
				contentList[i].Status = 0
			} else {
				contentList[i].Status = 1
			}
			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(map[string]string{"status": "success"})
			return
		}
	}
	http.Error(w, "Not Found", http.StatusNotFound)
}

// 删除处理器
func handleDelete(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	mu.Lock()
	defer mu.Unlock()

	id, _ := strconv.Atoi(r.FormValue("id"))
	for i, v := range contentList {
		if v.ID == id {
			contentList = append(contentList[:i], contentList[i+1:]...)
			w.Header().Set("Content-Type", "application/json")
			json.NewEncoder(w).Encode(map[string]string{"status": "success"})
			return
		}
	}
	http.Error(w, "Not Found", http.StatusNotFound)
}

2. 前端深色主题 HTML 模板 (内联于 Go 中)

以下是嵌入在 Go 中的网页模板。采用极简、极酷的暗黑风格(Dark Mode),无需引入任何外部 CSS 或 JS 文件,确保纯原生、轻量:

const htmlTemplate = `
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI 生成内容管理后台</title>
    <style>
        /* 极简深色主题样式 - 绝无外部依赖 */
        body {
            background-color: #121212;
            color: #e0e0e0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #2d2d2d;
            padding-bottom: 15px;
            margin-bottom: 20px;
        }
        h1 {
            font-size: 24px;
            color: #ffffff;
            margin: 0;
        }
        .stats {
            font-size: 14px;
            color: #888;
        }
        /* 表格样式 */
        .table-container {
            background-color: #1e1e1e;
            border-radius: 8px;
            overflow-x: auto;
            border: 1px solid #2d2d2d;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            text-align: left;
        }
        th, td {
            padding: 14px 16px;
            border-bottom: 1px solid #2d2d2d;
            font-size: 14px;
        }
        th {
            background-color: #252525;
            color: #aaa;
            font-weight: 600;
        }
        tr:hover {
            background-color: #252525;
        }
        .badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        .badge-active {
            background-color: #1b5e20;
            color: #4caf50;
        }
        .badge-disabled {
            background-color: #b71c1c;
            color: #f44336;
        }
        /* 按钮样式 */
        .btn {
            background-color: #333;
            color: #fff;
            border: none;
            padding: 6px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 13px;
            transition: background-color 0.2s;
            margin-right: 5px;
        }
        .btn:hover {
            background-color: #444;
        }
        .btn-danger {
            background-color: #c62828;
        }
        .btn-danger:hover {
            background-color: #d32f2f;
        }
        .btn-primary {
            background-color: #1565c0;
        }
        .btn-primary:hover {
            background-color: #1976d2;
        }

        /* ===== 重点:完美自动折行分页按钮组 ===== */
        .pagination-container {
            margin-top: 25px;
            display: flex;
            justify-content: center;
        }
        .pagination {
            display: flex;
            flex-wrap: wrap;       /* 开启自动折行! */
            gap: 6px;              /* 按钮之间的上下左右间距 */
            max-width: 90%;        /* 限制最大宽度,保证折行效果明显 */
            justify-content: center;
            padding: 10px;
        }
        .page-item {
            display: inline-block;
        }
        .page-link {
            display: block;
            background-color: #252525;
            color: #bbb;
            text-decoration: none;
            padding: 8px 14px;
            border-radius: 4px;
            font-size: 14px;
            border: 1px solid #333;
            transition: all 0.2s;
        }
        .page-link:hover {
            background-color: #333;
            color: #fff;
            border-color: #555;
        }
        .page-item.active .page-link {
            background-color: #1565c0;
            color: #fff;
            border-color: #1976d2;
        }
    </style>
</head>
<body>
    <div class="container">
        <header>
            <div>
                <h1>AI 语料及百科数据管理后台</h1>
                <p style="margin: 5px 0 0 0; color: #888; font-size: 13px;">数据状态变更与物理删除管理</p>
            </div>
            <div class="stats">
                共 <strong>{{.TotalCount}}</strong> 条生成记录
            </div>
        </header>

        <!-- 数据表格 -->
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th width="80">ID</th>
                        <th width="200">标题</th>
                        <th>Prompt 提示词</th>
                        <th width="100">状态</th>
                        <th width="150">生成时间</th>
                        <th width="180">操作</th>
                    </tr>
                </thead>
                <tbody>
                    {{range .List}}
                    <tr id="row-{{.ID}}">
                        <td>{{.ID}}</td>
                        <td style="font-weight: 500; color: #fff;">{{.Title}}</td>
                        <td style="color: #aaa; font-size: 13px; max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{.Prompt}}</td>
                        <td>
                            {{if eq .Status 1}}
                            <span class="badge badge-active" id="badge-{{.ID}}">已启用</span>
                            {{else}}
                            <span class="badge badge-disabled" id="badge-{{.ID}}">已禁用</span>
                            {{--end}}
                        </td>
                        <td style="color: #888;">{{.CreatedAt}}</td>
                        <td>
                            <button class="btn btn-primary" onclick="toggleStatus({{.ID}})">切状态</button>
                            <button class="btn btn-danger" onclick="deleteRow({{.ID}})">删除</button>
                        </td>
                    </tr>
                    {{else}}
                    <tr>
                        <td colspan="6" style="text-align: center; color: #888; padding: 40px;">暂无数据</td>
                    </tr>
                    {{end}}
                </tbody>
            </table>
        </div>

        <!-- 分页部分 -->
        <div class="pagination-container">
            <div class="pagination">
                {{$currentPage := .CurrentPage}}
                {{range .Pages}}
                <div class="page-item {{if eq . $currentPage}}active{{end}}">
                    <a href="/admin/ai/list?page={{.}}" class="page-link">{{.}}</a>
                </div>
                {{end}}
            </div>
        </div>
    </div>

    <!-- 原生免库 AJAX 操作交互 -->
    <script>
        function toggleStatus(id) {
            const formData = new FormData();
            formData.append('id', id);

            fetch('/admin/ai/toggle', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    const badge = document.getElementById('badge-' + id);
                    if (badge.classList.contains('badge-active')) {
                        badge.classList.remove('badge-active');
                        badge.classList.add('badge-disabled');
                        badge.innerText = '已禁用';
                    } else {
                        badge.classList.remove('badge-disabled');
                        badge.classList.add('badge-active');
                        badge.innerText = '已启用';
                    }
                } else {
                    alert('切换状态失败');
                }
            }).catch(() => alert('网络异常'));
        }

        function deleteRow(id) {
            if (!confirm('确定要彻底删除该条AI内容吗?')) return;

            const formData = new FormData();
            formData.append('id', id);

            fetch('/admin/ai/delete', {
                method: 'POST',
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    const row = document.getElementById('row-' + id);
                    row.style.transition = 'all 0.3s';
                    row.style.opacity = '0';
                    setTimeout(() => {
                        row.remove();
                        // 刷新页面以便让分页器重新计算数量,或保持当前页
                        location.reload();
                    }, 300);
                } else {
                    alert('删除失败');
                }
            }).catch(() => alert('网络异常'));
        }
    </script>
</body>
</html>
`

解决痛点的核心 CSS 解析

.pagination {
    display: flex;
    flex-wrap: wrap;       /* 1. 核心:允许子元素在空间不足时向下换行 */
    gap: 6px;              /* 2. 核心:设置按钮换行后的上下间距以及左右间距 */
    max-width: 90%;        /* 3. 核心:设定边界容器,强制多页码时折行 */
    justify-content: center; 
}
  • 为什么以前会往右拉伸? 因为默认的 display: block 或者 flex 容器在没有设置 flex-wrap 时,其默认值是 nowrap。当页数多时,所有按钮会被强行挤在一排,撑爆容器产生横向滚动条。
  • 现在的效果: 哪怕有 100 页,按钮也会像文字一样,写满一排自动换下一排,完美对齐,美观整洁!