合作页面的内容

This commit is contained in:
李琦
2026-01-16 10:19:30 +08:00
parent 3bcef22487
commit de821a8645
18 changed files with 1018 additions and 237 deletions

View File

@@ -141,6 +141,11 @@ const menuItems = ref<MenuItem[]>([
icon: '📊',
path: '/admin/dashboard'
},
{
title: '数据分析',
icon: '📈',
path: '/admin/analytics'
},
{
title: '内容管理',
icon: '📚',
@@ -269,7 +274,7 @@ onUnmounted(() => {
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 0.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
z-index: 100;
z-index: 9999;
overflow: hidden;
animation: slideIn 0.2s ease-out;
}

View File

@@ -17,7 +17,7 @@
>{{ label }}</label>
<!-- Autocomplete Dropdown -->
<div v-if="showDropdown && suggestions.length > 0" class="absolute z-50 left-0 right-0 top-full mt-1 bg-[#1a1a1a] border border-white/10 shadow-lg max-h-48 overflow-y-auto rounded-b-md">
<div v-if="showDropdown && suggestions.length > 0" class="absolute z-[9999] left-0 right-0 top-full mt-1 bg-[#1a1a1a] border border-white/10 shadow-lg max-h-48 overflow-y-auto rounded-b-md">
<div
v-for="(suggestion, index) in suggestions"
:key="index"

View File

@@ -0,0 +1,385 @@
<template>
<div class="analytics-page">
<div class="page-header flex justify-between items-center mb-6">
<h1 class="text-2xl font-bold text-[#d4b383]">数据分析</h1>
<div class="date-filter flex gap-2">
<div class="quick-select flex bg-white/5 rounded-lg p-1 border border-white/10">
<button
v-for="range in dateRanges"
:key="range.value"
@click="selectRange(range.value)"
class="px-3 py-1 text-sm rounded transition-colors"
:class="selectedRange === range.value ? 'bg-[#d4b383] text-black' : 'text-white/60 hover:text-white'"
>
{{ range.label }}
</button>
</div>
<div class="custom-date flex gap-2 items-center">
<!-- 使用datetime-local以支持精确到分钟虽然这里主要用日期但预留接口 -->
<input type="datetime-local" v-model="startDateTime" class="bg-white/5 border border-white/10 rounded px-2 py-1 text-white text-sm outline-none focus:border-[#d4b383]" @change="validateDates">
<span class="text-white/40">-</span>
<input type="datetime-local" v-model="endDateTime" class="bg-white/5 border border-white/10 rounded px-2 py-1 text-white text-sm outline-none focus:border-[#d4b383]" @change="validateDates">
<button @click="clearDates" class="px-2 py-1 text-white/40 hover:text-white text-sm" title="清空"></button>
<button @click="handleSearch" class="px-3 py-1 bg-[#d4b383]/20 text-[#d4b383] border border-[#d4b383]/50 rounded text-sm hover:bg-[#d4b383]/30 transition-colors" :disabled="loading">
{{ loading ? '加载中...' : '查询' }}
</button>
</div>
</div>
</div>
<div v-if="dateError" class="mb-4 p-3 bg-red-500/10 border border-red-500/20 text-red-400 rounded-lg text-sm">
{{ dateError }}
</div>
<!-- Charts Row 1 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
<!-- New Posts Trend -->
<div class="chart-card relative">
<h3 class="chart-title">新增博文趋势</h3>
<div class="h-80" v-if="!loading && hasData(stats.postsTrend)">
<v-chart class="chart" :option="postsTrendOption" autoresize />
</div>
<div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
加载中...
</div>
<div v-else class="h-80 flex items-center justify-center text-white/20">
暂无数据
</div>
</div>
<!-- UV Trend -->
<div class="chart-card relative">
<h3 class="chart-title">访客趋势 (UV)</h3>
<div class="h-80" v-if="!loading && hasData(stats.uvTrend)">
<v-chart class="chart" :option="uvTrendOption" autoresize />
</div>
<div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
加载中...
</div>
<div v-else class="h-80 flex items-center justify-center text-white/20">
暂无数据
</div>
</div>
</div>
<!-- Charts Row 2 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- User Regions -->
<div class="chart-card relative">
<h3 class="chart-title">用户地域分布</h3>
<div class="h-80" v-if="!loading && hasData(stats.userRegions)">
<v-chart class="chart" :option="regionOption" autoresize />
</div>
<div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
加载中...
</div>
<div v-else class="h-80 flex items-center justify-center text-white/20">
暂无数据
</div>
</div>
<!-- Top Posts -->
<div class="chart-card relative">
<h3 class="chart-title">热门文章 Top 5</h3>
<div class="h-80" v-if="!loading && hasData(stats.topPosts)">
<v-chart class="chart" :option="topPostsOption" autoresize />
</div>
<div v-else-if="loading" class="h-80 flex items-center justify-center text-white/20">
加载中...
</div>
<div v-else class="h-80 flex items-center justify-center text-white/20">
暂无数据
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { getDashboardStats } from '../../../services/api'
import { useToast } from '../../../composables/useToast'
use([
CanvasRenderer,
BarChart,
LineChart,
PieChart,
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
])
const toast = useToast()
const stats = ref<any>({})
const loading = ref(false)
const selectedRange = ref('7d')
const startDateTime = ref('')
const endDateTime = ref('')
const dateError = ref('')
const dateRanges = [
{ label: '今日', value: 'today' },
{ label: '本周', value: 'week' },
{ label: '本月', value: 'month' },
{ label: '近7天', value: '7d' },
{ label: '近30天', value: '30d' },
{ label: '近一年', value: '1y' }
]
const hasData = (data: any[]) => {
return data && data.length > 0
}
const selectRange = (value: string) => {
selectedRange.value = value
const end = new Date()
const start = new Date()
if (value === 'today') {
start.setHours(0, 0, 0, 0)
end.setHours(23, 59, 59, 999)
} else if (value === 'week') {
const day = start.getDay() || 7 // Get current day number, make Sunday 7
if (day !== 1) start.setHours(-24 * (day - 1)) // Set to Monday
else start.setHours(0,0,0,0)
} else if (value === 'month') {
start.setDate(1)
start.setHours(0,0,0,0)
} else if (value === '7d') {
start.setDate(end.getDate() - 6)
} else if (value === '30d') {
start.setDate(end.getDate() - 29)
} else if (value === '1y') {
start.setFullYear(end.getFullYear() - 1)
}
startDateTime.value = formatDateTime(start)
endDateTime.value = formatDateTime(end)
dateError.value = ''
loadData()
}
const formatDateTime = (date: Date) => {
// YYYY-MM-DDTHH:mm
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day}T${hours}:${minutes}`
}
const validateDates = () => {
if (startDateTime.value && endDateTime.value) {
if (new Date(startDateTime.value) > new Date(endDateTime.value)) {
dateError.value = '开始时间不能晚于结束时间'
return false
}
}
dateError.value = ''
return true
}
const clearDates = () => {
startDateTime.value = ''
endDateTime.value = ''
selectedRange.value = ''
loadData()
}
const handleSearch = () => {
if (validateDates()) {
selectedRange.value = '' // Clear preset selection when manual search
loadData()
}
}
// Chart Options
const postsTrendOption = computed(() => ({
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(0,0,0,0.8)',
borderColor: '#333',
textStyle: { color: '#fff' },
formatter: function(params: any) {
let result = params[0].name + '<br/>';
params.forEach((item: any) => {
const data = stats.value.postsTrend[item.dataIndex];
result += item.marker + item.seriesName + ': ' + item.value + ' 篇<br/>';
// if (data.yoy) result += '同比: ' + data.yoy + '%<br/>';
// if (data.mom) result += '环比: ' + data.mom + '%<br/>';
});
return result;
}
},
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: {
type: 'category',
data: stats.value.postsTrend?.map((i: any) => i.date) || [],
axisLabel: { color: '#ccc' }
},
yAxis: {
type: 'value',
axisLabel: { color: '#ccc' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
series: [{
name: '新增文章',
data: stats.value.postsTrend?.map((i: any) => i.value) || [],
type: 'line',
smooth: true,
itemStyle: { color: '#3b82f6' },
areaStyle: { color: 'rgba(59, 130, 246, 0.1)' }
}]
}))
const uvTrendOption = computed(() => ({
tooltip: {
trigger: 'axis',
backgroundColor: 'rgba(0,0,0,0.8)',
borderColor: '#333',
textStyle: { color: '#fff' }
},
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: {
type: 'category',
data: stats.value.uvTrend?.map((i: any) => i.date) || [],
axisLabel: { color: '#ccc' }
},
yAxis: {
type: 'value',
axisLabel: { color: '#ccc' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
series: [{
name: '访客数 (UV)',
data: stats.value.uvTrend?.map((i: any) => i.value) || [],
type: 'bar',
itemStyle: { color: '#10b981' },
barWidth: '40%'
}]
}))
const regionOption = computed(() => ({
tooltip: {
trigger: 'item',
backgroundColor: 'rgba(0,0,0,0.8)',
borderColor: '#333',
textStyle: { color: '#fff' },
formatter: '{b}: {c} ({d}%)'
},
legend: {
orient: 'vertical',
left: 'left',
textStyle: { color: '#ccc' }
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#050505',
borderWidth: 2
},
label: { show: false, position: 'center' },
emphasis: {
label: { show: true, fontSize: 20, fontWeight: 'bold', color: '#fff' }
},
labelLine: { show: false },
data: stats.value.userRegions?.map((i: any) => ({ value: i.Count, name: i.Region })) || []
}
]
}))
const topPostsOption = computed(() => ({
tooltip: {
trigger: 'axis',
axisPointer: { type: 'shadow' },
backgroundColor: 'rgba(0,0,0,0.8)',
borderColor: '#333',
textStyle: { color: '#fff' }
},
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: {
type: 'value',
axisLabel: { color: '#ccc' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
yAxis: {
type: 'category',
data: stats.value.topPosts?.map((i: any) => i.title.length > 10 ? i.title.substring(0, 10) + '...' : i.title) || [],
axisLabel: { color: '#ccc' }
},
series: [
{
name: '阅读量',
type: 'bar',
data: stats.value.topPosts?.map((i: any) => i.count) || [],
itemStyle: { color: '#d4b383' }
}
]
}))
const loadData = async () => {
loading.value = true
try {
// Convert datetime-local format to API expected format if needed
// Assuming API accepts YYYY-MM-DD or YYYY-MM-DD HH:mm:ss
const start = startDateTime.value.replace('T', ' ')
const end = endDateTime.value.replace('T', ' ')
stats.value = await getDashboardStats(start, end)
} catch (error) {
console.error(error)
toast.showToast('加载数据失败', 'error')
} finally {
loading.value = false
}
}
onMounted(() => {
// Default to 7 days
selectRange('7d')
})
</script>
<style scoped>
.analytics-page {
width: 100%;
}
.chart-card {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 0.75rem;
padding: 1.5rem;
}
.chart-title {
font-size: 1.1rem;
color: #d4b383;
margin: 0 0 1rem 0;
font-weight: 500;
}
.chart {
height: 100%;
width: 100%;
}
</style>

View File

@@ -13,7 +13,6 @@
<div class="stat-icon bg-green-500/10 text-green-400">👥</div>
<div class="stat-info">
<h3>今日访客 (UV)</h3>
<!-- 这里应该展示今日UV目前API返回的是列表需要处理 -->
<p>{{ todayUV }}</p>
</div>
</div>
@@ -28,46 +27,52 @@
<div class="stat-icon bg-yellow-500/10 text-yellow-400">🎨</div>
<div class="stat-info">
<h3>作品展示</h3>
<!-- 暂时没有返回作品数先占位 -->
<p>-</p>
<p>{{ stats.works || '-' }}</p>
</div>
</div>
</div>
<!-- Charts Row 1 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
<!-- New Posts Trend -->
<div class="chart-card">
<h3 class="chart-title">近7天新增博文</h3>
<div class="h-80">
<v-chart class="chart" :option="postsTrendOption" autoresize />
</div>
</div>
<!-- UV Trend -->
<div class="chart-card">
<h3 class="chart-title">近7天访客趋势</h3>
<div class="h-80">
<v-chart class="chart" :option="uvTrendOption" autoresize />
</div>
</div>
</div>
<!-- Charts Row 2 -->
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<!-- User Regions -->
<div class="chart-card">
<h3 class="chart-title">用户地域分布</h3>
<div class="h-80">
<v-chart class="chart" :option="regionOption" autoresize />
<!-- Recent Activities -->
<div class="bg-white/5 border border-white/10 rounded-xl p-6 backdrop-blur-sm">
<h3 class="text-lg font-medium text-[#d4b383] mb-4">最近日志</h3>
<div class="space-y-4">
<div v-for="log in operationLogs" :key="log.id" class="flex items-start gap-4 p-3 bg-white/5 rounded-lg border border-white/5">
<div class="w-8 h-8 rounded-full bg-[#d4b383]/10 flex items-center justify-center text-[#d4b383] text-sm shrink-0">
{{ log.method }}
</div>
<div class="flex-1 min-w-0">
<div class="flex justify-between items-start mb-1">
<span class="text-sm font-medium text-white truncate">{{ log.username }}</span>
<span class="text-xs text-white/40 whitespace-nowrap">{{ formatDate(log.createdAt) }}</span>
</div>
<p class="text-xs text-white/60 truncate font-mono">{{ log.path }}</p>
</div>
</div>
<div v-if="operationLogs.length === 0" class="text-center text-white/40 py-4">暂无日志</div>
</div>
</div>
<!-- Top Posts -->
<div class="chart-card">
<h3 class="chart-title">热门文章 Top 5</h3>
<div class="h-80">
<v-chart class="chart" :option="topPostsOption" autoresize />
<!-- Blog Updates -->
<div class="bg-white/5 border border-white/10 rounded-xl p-6 backdrop-blur-sm">
<h3 class="text-lg font-medium text-[#d4b383] mb-4">博文动态</h3>
<div class="space-y-4">
<div v-for="post in recentPosts" :key="post.id" class="flex items-start gap-4 p-3 bg-white/5 rounded-lg border border-white/5">
<div class="w-8 h-8 rounded-full bg-blue-500/10 flex items-center justify-center text-blue-400 text-sm shrink-0">
📝
</div>
<div class="flex-1 min-w-0">
<div class="flex justify-between items-start mb-1">
<span class="text-sm font-medium text-white truncate">{{ post.title }}</span>
<span class="text-xs text-white/40 whitespace-nowrap">{{ formatDate(post.date) }}</span>
</div>
<div class="flex items-center gap-2 mt-1">
<span class="px-2 py-0.5 rounded text-[10px] bg-white/10 text-white/60">{{ post.category }}</span>
<span class="text-[10px] text-white/40">👁 {{ post.readCount || 0 }}</span>
</div>
</div>
</div>
<div v-if="recentPosts.length === 0" class="text-center text-white/40 py-4">暂无动态</div>
</div>
</div>
</div>
@@ -76,132 +81,38 @@
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { getDashboardStats } from '../../../services/api'
use([
CanvasRenderer,
BarChart,
LineChart,
PieChart,
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
])
import { getDashboardStats, getOperationLogs, fetchPosts } from '../../../services/api'
const stats = ref<any>({})
const operationLogs = ref<any[]>([])
const recentPosts = ref<any[]>([])
const todayUV = computed(() => {
// Use dashboard stats for UV if available, otherwise 0
if (!stats.value.uvTrend || stats.value.uvTrend.length === 0) return 0
return stats.value.uvTrend[stats.value.uvTrend.length - 1].Count
// Note: uvTrend uses {date, value} now
return stats.value.uvTrend[stats.value.uvTrend.length - 1].value
})
// Chart Options
const postsTrendOption = computed(() => ({
tooltip: { trigger: 'axis' },
xAxis: {
type: 'category',
data: stats.value.postsTrend?.map((i: any) => i.Date) || [],
axisLabel: { color: '#ccc' }
},
yAxis: {
type: 'value',
axisLabel: { color: '#ccc' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
series: [{
data: stats.value.postsTrend?.map((i: any) => i.Count) || [],
type: 'line',
smooth: true,
itemStyle: { color: '#3b82f6' },
areaStyle: { color: 'rgba(59, 130, 246, 0.1)' }
}]
}))
const uvTrendOption = computed(() => ({
tooltip: { trigger: 'axis' },
xAxis: {
type: 'category',
data: stats.value.uvTrend?.map((i: any) => i.Date) || [],
axisLabel: { color: '#ccc' }
},
yAxis: {
type: 'value',
axisLabel: { color: '#ccc' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
series: [{
data: stats.value.uvTrend?.map((i: any) => i.Count) || [],
type: 'bar',
itemStyle: { color: '#10b981' },
barWidth: '40%'
}]
}))
const regionOption = computed(() => ({
tooltip: { trigger: 'item' },
legend: {
orient: 'vertical',
left: 'left',
textStyle: { color: '#ccc' }
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: {
borderRadius: 10,
borderColor: '#050505',
borderWidth: 2
},
label: { show: false, position: 'center' },
emphasis: {
label: { show: true, fontSize: 20, fontWeight: 'bold', color: '#fff' }
},
labelLine: { show: false },
data: stats.value.userRegions?.map((i: any) => ({ value: i.Count, name: i.Region })) || []
}
]
}))
const topPostsOption = computed(() => ({
tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
xAxis: {
type: 'value',
axisLabel: { color: '#ccc' },
splitLine: { lineStyle: { color: 'rgba(255,255,255,0.1)' } }
},
yAxis: {
type: 'category',
data: stats.value.topPosts?.map((i: any) => i.title.substring(0, 10) + '...') || [],
axisLabel: { color: '#ccc' }
},
series: [
{
name: '阅读量',
type: 'bar',
data: stats.value.topPosts?.map((i: any) => i.readCount) || [],
itemStyle: { color: '#d4b383' }
}
]
}))
const formatDate = (dateStr: string) => {
if (!dateStr) return ''
const date = new Date(dateStr)
return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
}
const loadData = async () => {
try {
stats.value = await getDashboardStats()
// Parallel requests
const [statsData, logsData, postsData] = await Promise.all([
getDashboardStats(), // Default 7 days
getOperationLogs(1, 5), // Get last 5 logs
fetchPosts() // Get posts, we'll slice top 5
])
stats.value = statsData
operationLogs.value = logsData.list
recentPosts.value = postsData.slice(0, 5)
} catch (error) {
console.error(error)
}
@@ -250,24 +161,4 @@ onMounted(() => {
color: #fff;
margin: 0;
}
.chart-card {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 0.75rem;
padding: 1.5rem;
}
.chart-title {
font-size: 1.1rem;
color: #d4b383;
margin: 0 0 1rem 0;
font-weight: 500;
}
.chart {
height: 100%;
width: 100%;
}
</style>

View File

@@ -22,6 +22,7 @@ const routes = [
// 仪表盘
{ path: '', redirect: '/admin/dashboard' },
{ path: 'dashboard', name: 'admin-dashboard', component: () => import('./pages/admin/dashboard/Overview.vue') },
{ path: 'analytics', name: 'admin-analytics', component: () => import('./pages/admin/dashboard/Analytics.vue') },
// 用户管理
{ path: 'users', name: 'admin-users', component: () => import('./pages/admin/Users.vue') },

View File

@@ -734,16 +734,23 @@ export interface RecentActivity {
}
// 仪表盘API
export const getDashboardStats = async (): Promise<DashboardStats> => {
export const getDashboardStats = async (startDate?: string, endDate?: string): Promise<DashboardStats> => {
try {
const response = await fetch(`${API_BASE}/admin/dashboard/stats`, {
let url = `${API_BASE}/admin/dashboard/stats`
const params = new URLSearchParams()
if (startDate) params.append('startDate', startDate)
if (endDate) params.append('endDate', endDate)
if (params.toString()) url += `?${params.toString()}`
const response = await fetch(url, {
headers: getAuthHeaders()
})
if (!response.ok) {
const errorData = await response.json()
throw new Error(errorData.error || '获取仪表盘统计数据失败')
}
return await response.json()
const data = await response.json()
return data.result // 适配新的统一响应结构
} catch (error) {
console.error('Get dashboard stats error:', error)
throw error

View File

@@ -1,36 +1,31 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/niangaodev/art-code/config"
"github.com/niangaodev/art-code/repositories"
"github.com/niangaodev/art-code/utils"
)
// GetDashboardStats 获取仪表盘统计数据
func GetDashboardStats(c *gin.Context) {
// 1. 获取博文增长趋势 (最近7天新增)
postsTrend, err := repositories.GetNewPostsTrend()
startDate := c.Query("startDate")
endDate := c.Query("endDate")
// 1. 获取博文增长趋势
postsTrend, err := repositories.GetNewPostsTrend(startDate, endDate)
if err != nil {
postsTrend = []struct {
Date string
Count int
}{} // Fallback empty
postsTrend = []repositories.TrendData{} // Fallback empty
}
// 2. 获取今日访客UV (根据IP)
// 这里可以复用GetDailyUV获取最近7天取最后一天即为今日或者根据前端需要展示7天趋势
uvTrend, err := repositories.GetDailyUV()
// 2. 获取访客UV (根据IP)
uvTrend, err := repositories.GetDailyUV(startDate, endDate)
if err != nil {
uvTrend = []struct {
Date string
Count int
}{}
uvTrend = []repositories.UVTrendData{}
}
// 3. 用户画像-地域分布
userRegions, err := repositories.GetUserRegions()
userRegions, err := repositories.GetUserRegions(startDate, endDate)
if err != nil {
userRegions = []struct {
Region string
@@ -39,21 +34,53 @@ func GetDashboardStats(c *gin.Context) {
}
// 4. 热门文章 Top 5
// 需要在Post repository增加方法
topPosts, err := repositories.GetTopPosts(5)
if err != nil {
topPosts = nil // Fallback
// 优先使用访问日志统计如果没有则回退到posts表的read_count
topPosts, err := repositories.GetTopArticlesByAccess(5)
if err != nil || len(topPosts) == 0 {
// Fallback to post.read_count
dbPosts, err := repositories.GetTopPosts(5)
if err == nil {
// Convert models.Post to the struct structure
// Create a temporary structure slice
topPosts = make([]struct {
ArticleID int `json:"article_id"`
Title string `json:"title"`
Count int `json:"count"`
}, 0)
for _, p := range dbPosts {
topPosts = append(topPosts, struct {
ArticleID int `json:"article_id"`
Title string `json:"title"`
Count int `json:"count"`
}{
ArticleID: int(p.ID),
Title: p.Title,
Count: int(p.ReadCount),
})
}
}
}
// 5. 合作咨询总数
var inquiryCount int
config.DB.QueryRow("SELECT COUNT(*) FROM inquiries").Scan(&inquiryCount)
c.JSON(http.StatusOK, gin.H{
// 6. 作品总数
var workCount int
// 假设 works 表存在,如果没有则返回 0
config.DB.QueryRow("SELECT COUNT(*) FROM works").Scan(&workCount)
// 7. 文章总数
var postCount int
config.DB.QueryRow("SELECT COUNT(*) FROM posts").Scan(&postCount)
utils.Success(c, gin.H{
"postsTrend": postsTrend,
"uvTrend": uvTrend,
"userRegions": userRegions,
"topPosts": topPosts,
"inquiryCount": inquiryCount,
"posts": postCount,
"works": workCount,
})
}

View File

@@ -8,6 +8,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/niangaodev/art-code/models"
"github.com/niangaodev/art-code/repositories"
"github.com/niangaodev/art-code/utils"
)
// 获取博客文章列表
@@ -52,6 +53,32 @@ func GetPost(c *gin.Context) {
// 构建响应,包含内容
response := repositories.BuildPostResponse(post, true)
// 记录用户访问日志 (异步执行,不阻塞响应)
go func() {
// 获取客户端IP
ip := c.ClientIP()
// 获取归属地
location := utils.GetRegion(ip)
// 获取用户ID (如果已登录)
var userID uint = 0
if uid, exists := c.Get("userID"); exists {
userID = uid.(uint)
}
logEntry := &models.UserAccessLog{
UserID: userID,
UserIP: ip,
UserLocation: location,
ArticleID: post.ID,
}
if err := repositories.CreateUserAccessLog(logEntry); err != nil {
log.Printf("Failed to create access log: %v", err)
}
}()
c.JSON(http.StatusOK, response)
}

View File

@@ -112,7 +112,7 @@ func main() {
// 文章管理
authAdmin.GET("/posts", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPosts)
authAdmin.POST("/posts", middleware.PermissionMiddleware("posts", "create"), handlers.CreatePost)
authAdmin.POST("/posts", middleware.PermissionMiddleware("posts", "create"), handlers.AdminCreatePost)
authAdmin.PUT("/posts/:id", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdatePost)
authAdmin.DELETE("/posts/:id", middleware.PermissionMiddleware("posts", "delete"), handlers.AdminDeletePost)
@@ -124,7 +124,7 @@ func main() {
authAdmin.GET("/operation-logs", middleware.PermissionMiddleware("operation_logs", "read"), handlers.AdminGetOperationLogs)
// 仪表盘数据
authAdmin.GET("/dashboard/stats", middleware.PermissionMiddleware("dashboard", "read"), handlers.AdminGetDashboardStats)
// authAdmin.GET("/dashboard/stats", middleware.PermissionMiddleware("dashboard", "read"), handlers.GetDashboardStats) // Duplicate removed
authAdmin.GET("/dashboard/activities", middleware.PermissionMiddleware("dashboard", "read"), handlers.AdminGetRecentActivities)
// 标签管理

31
server/middleware/cors.go Normal file
View File

@@ -0,0 +1,31 @@
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
// CorsMiddleware 处理跨域请求中间件
func CorsMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin")
if origin != "" {
// 允许所有来源,生产环境建议配置为具体的域名
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
}
// 放行所有OPTIONS方法
if method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
}
c.Next()
}
}

View File

@@ -0,0 +1,13 @@
package models
import "time"
// UserAccessLog 用户访问记录模型
type UserAccessLog struct {
ID uint `json:"id"`
UserID uint `json:"user_id"` // 用户ID未登录用户为0
UserIP string `json:"user_ip"` // 用户IP地址
UserLocation string `json:"user_location"` // 用户归属地
ArticleID uint `json:"article_id"` // 访问的文章ID
AccessTime time.Time `json:"access_time"` // 访问时间
}

View File

@@ -11,7 +11,7 @@
Target Server Version : 80407 (8.4.7)
File Encoding : 65001
Date: 16/01/2026 09:08:18
Date: 16/01/2026 10:18:46
*/
SET NAMES utf8mb4;
@@ -132,7 +132,7 @@ CREATE TABLE `operation_logs` (
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_user_id`(`user_id` ASC) USING BTREE,
INDEX `idx_created_at`(`created_at` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 108 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '操作日志表' ROW_FORMAT = DYNAMIC;
) ENGINE = InnoDB AUTO_INCREMENT = 196 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = '操作日志表' ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of operation_logs
@@ -244,6 +244,94 @@ INSERT INTO `operation_logs` VALUES (104, 1, 'lq', '::1', '/api/admin/operation-
INSERT INTO `operation_logs` VALUES (105, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 47, '2026-01-16 09:05:16');
INSERT INTO `operation_logs` VALUES (106, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 49, '2026-01-16 09:05:22');
INSERT INTO `operation_logs` VALUES (107, 1, 'lq', '::1', '/api/admin/dashboard/activities', 'GET', '', 200, 49, '2026-01-16 09:05:22');
INSERT INTO `operation_logs` VALUES (108, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 48, '2026-01-16 09:13:46');
INSERT INTO `operation_logs` VALUES (109, 1, 'lq', '::1', '/api/admin/works', 'GET', '', 200, 227, '2026-01-16 09:13:48');
INSERT INTO `operation_logs` VALUES (110, 1, 'lq', '::1', '/api/admin/snippets', 'GET', '', 200, 46, '2026-01-16 09:13:49');
INSERT INTO `operation_logs` VALUES (111, 1, 'lq', '::1', '/api/admin/tags', 'GET', '', 200, 43, '2026-01-16 09:13:50');
INSERT INTO `operation_logs` VALUES (112, 1, 'lq', '::1', '/api/admin/snippets', 'GET', '', 200, 45, '2026-01-16 09:13:51');
INSERT INTO `operation_logs` VALUES (113, 1, 'lq', '::1', '/api/admin/snippets', 'GET', '', 200, 50, '2026-01-16 09:13:59');
INSERT INTO `operation_logs` VALUES (114, 1, 'lq', '::1', '/api/admin/email-suffixes', 'GET', '', 200, 45, '2026-01-16 09:14:06');
INSERT INTO `operation_logs` VALUES (115, 1, 'lq', '::1', '/api/admin/email-suffixes', 'GET', '', 200, 55, '2026-01-16 09:15:10');
INSERT INTO `operation_logs` VALUES (116, 1, 'lq', '::1', '/api/admin/roles', 'GET', '', 200, 142, '2026-01-16 09:15:16');
INSERT INTO `operation_logs` VALUES (117, 1, 'lq', '::1', '/api/admin/users', 'GET', '', 200, 46, '2026-01-16 09:15:19');
INSERT INTO `operation_logs` VALUES (118, 1, 'lq', '::1', '/api/admin/roles', 'GET', '', 200, 138, '2026-01-16 09:15:20');
INSERT INTO `operation_logs` VALUES (119, 1, 'lq', '::1', '/api/admin/users', 'GET', '', 200, 46, '2026-01-16 09:15:23');
INSERT INTO `operation_logs` VALUES (120, 1, 'lq', '::1', '/api/admin/settings', 'GET', '', 200, 47, '2026-01-16 09:15:29');
INSERT INTO `operation_logs` VALUES (121, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 47, '2026-01-16 09:15:30');
INSERT INTO `operation_logs` VALUES (122, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 47, '2026-01-16 09:15:33');
INSERT INTO `operation_logs` VALUES (123, 1, 'lq', '::1', '/api/admin/dashboard/activities', 'GET', '', 200, 45, '2026-01-16 09:15:33');
INSERT INTO `operation_logs` VALUES (124, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 50, '2026-01-16 09:25:08');
INSERT INTO `operation_logs` VALUES (125, 1, 'lq', '::1', '/api/admin/dashboard/activities', 'GET', '', 200, 50, '2026-01-16 09:25:08');
INSERT INTO `operation_logs` VALUES (126, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 52, '2026-01-16 09:25:23');
INSERT INTO `operation_logs` VALUES (127, 1, 'lq', '::1', '/api/admin/dashboard/activities', 'GET', '', 200, 46, '2026-01-16 09:25:23');
INSERT INTO `operation_logs` VALUES (128, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 53, '2026-01-16 09:26:23');
INSERT INTO `operation_logs` VALUES (129, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 46, '2026-01-16 09:26:23');
INSERT INTO `operation_logs` VALUES (130, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 49, '2026-01-16 09:29:33');
INSERT INTO `operation_logs` VALUES (131, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 48, '2026-01-16 09:31:48');
INSERT INTO `operation_logs` VALUES (132, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 55, '2026-01-16 09:36:19');
INSERT INTO `operation_logs` VALUES (133, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 47, '2026-01-16 09:37:05');
INSERT INTO `operation_logs` VALUES (134, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 46, '2026-01-16 09:37:05');
INSERT INTO `operation_logs` VALUES (135, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 51, '2026-01-16 09:38:22');
INSERT INTO `operation_logs` VALUES (136, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 54, '2026-01-16 09:39:55');
INSERT INTO `operation_logs` VALUES (137, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 57, '2026-01-16 09:39:55');
INSERT INTO `operation_logs` VALUES (138, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 45, '2026-01-16 09:40:05');
INSERT INTO `operation_logs` VALUES (139, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 44, '2026-01-16 09:40:08');
INSERT INTO `operation_logs` VALUES (140, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 46, '2026-01-16 09:40:14');
INSERT INTO `operation_logs` VALUES (141, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 48, '2026-01-16 09:40:25');
INSERT INTO `operation_logs` VALUES (142, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 45, '2026-01-16 09:40:53');
INSERT INTO `operation_logs` VALUES (143, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 48, '2026-01-16 09:40:58');
INSERT INTO `operation_logs` VALUES (144, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 53, '2026-01-16 09:44:40');
INSERT INTO `operation_logs` VALUES (145, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 46, '2026-01-16 09:44:45');
INSERT INTO `operation_logs` VALUES (146, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 45, '2026-01-16 09:44:46');
INSERT INTO `operation_logs` VALUES (147, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 46, '2026-01-16 09:44:47');
INSERT INTO `operation_logs` VALUES (148, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 47, '2026-01-16 09:47:16');
INSERT INTO `operation_logs` VALUES (149, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 51, '2026-01-16 09:48:11');
INSERT INTO `operation_logs` VALUES (150, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 142, '2026-01-16 09:57:36');
INSERT INTO `operation_logs` VALUES (151, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 153, '2026-01-16 09:57:49');
INSERT INTO `operation_logs` VALUES (152, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 144, '2026-01-16 09:57:51');
INSERT INTO `operation_logs` VALUES (153, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 132, '2026-01-16 09:57:52');
INSERT INTO `operation_logs` VALUES (154, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 136, '2026-01-16 09:57:54');
INSERT INTO `operation_logs` VALUES (155, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 144, '2026-01-16 09:57:54');
INSERT INTO `operation_logs` VALUES (156, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 136, '2026-01-16 09:57:55');
INSERT INTO `operation_logs` VALUES (157, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 143, '2026-01-16 09:57:56');
INSERT INTO `operation_logs` VALUES (158, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 57, '2026-01-16 09:58:02');
INSERT INTO `operation_logs` VALUES (159, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 97, '2026-01-16 09:58:02');
INSERT INTO `operation_logs` VALUES (160, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 145, '2026-01-16 09:58:04');
INSERT INTO `operation_logs` VALUES (161, 1, 'lq', '::1', '/api/admin/posts', 'GET', '', 200, 46, '2026-01-16 09:58:04');
INSERT INTO `operation_logs` VALUES (162, 1, 'lq', '::1', '/api/admin/works', 'GET', '', 200, 242, '2026-01-16 09:58:05');
INSERT INTO `operation_logs` VALUES (163, 1, 'lq', '::1', '/api/admin/snippets', 'GET', '', 200, 49, '2026-01-16 09:58:07');
INSERT INTO `operation_logs` VALUES (164, 1, 'lq', '::1', '/api/admin/tags', 'GET', '', 200, 50, '2026-01-16 09:58:08');
INSERT INTO `operation_logs` VALUES (165, 1, 'lq', '::1', '/api/admin/about', 'GET', '', 200, 47, '2026-01-16 09:58:10');
INSERT INTO `operation_logs` VALUES (166, 1, 'lq', '::1', '/api/admin/works', 'GET', '', 200, 245, '2026-01-16 09:58:13');
INSERT INTO `operation_logs` VALUES (167, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 47, '2026-01-16 09:58:14');
INSERT INTO `operation_logs` VALUES (168, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 99, '2026-01-16 09:58:14');
INSERT INTO `operation_logs` VALUES (169, 1, 'lq', '::1', '/api/admin/works', 'GET', '', 200, 220, '2026-01-16 09:58:18');
INSERT INTO `operation_logs` VALUES (170, 1, 'lq', '::1', '/api/admin/snippets', 'GET', '', 200, 47, '2026-01-16 09:58:19');
INSERT INTO `operation_logs` VALUES (171, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 48, '2026-01-16 09:59:33');
INSERT INTO `operation_logs` VALUES (172, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 92, '2026-01-16 09:59:33');
INSERT INTO `operation_logs` VALUES (173, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 139, '2026-01-16 09:59:34');
INSERT INTO `operation_logs` VALUES (174, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 95, '2026-01-16 10:02:12');
INSERT INTO `operation_logs` VALUES (175, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 141, '2026-01-16 10:02:15');
INSERT INTO `operation_logs` VALUES (176, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 137, '2026-01-16 10:02:17');
INSERT INTO `operation_logs` VALUES (177, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 137, '2026-01-16 10:02:17');
INSERT INTO `operation_logs` VALUES (178, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 143, '2026-01-16 10:02:21');
INSERT INTO `operation_logs` VALUES (179, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 138, '2026-01-16 10:02:22');
INSERT INTO `operation_logs` VALUES (180, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 136, '2026-01-16 10:02:23');
INSERT INTO `operation_logs` VALUES (181, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 146, '2026-01-16 10:02:31');
INSERT INTO `operation_logs` VALUES (182, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 47, '2026-01-16 10:03:27');
INSERT INTO `operation_logs` VALUES (183, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 96, '2026-01-16 10:03:27');
INSERT INTO `operation_logs` VALUES (184, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 45, '2026-01-16 10:03:32');
INSERT INTO `operation_logs` VALUES (185, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 90, '2026-01-16 10:03:32');
INSERT INTO `operation_logs` VALUES (186, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 136, '2026-01-16 10:03:33');
INSERT INTO `operation_logs` VALUES (187, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 200, '2026-01-16 10:09:24');
INSERT INTO `operation_logs` VALUES (188, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 193, '2026-01-16 10:09:33');
INSERT INTO `operation_logs` VALUES (189, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 183, '2026-01-16 10:10:59');
INSERT INTO `operation_logs` VALUES (190, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 138, '2026-01-16 10:13:38');
INSERT INTO `operation_logs` VALUES (191, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 137, '2026-01-16 10:13:40');
INSERT INTO `operation_logs` VALUES (192, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 141, '2026-01-16 10:16:30');
INSERT INTO `operation_logs` VALUES (193, 1, 'lq', '::1', '/api/admin/operation-logs', 'GET', '', 200, 48, '2026-01-16 10:17:47');
INSERT INTO `operation_logs` VALUES (194, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 95, '2026-01-16 10:17:47');
INSERT INTO `operation_logs` VALUES (195, 1, 'lq', '::1', '/api/admin/dashboard/stats', 'GET', '', 200, 137, '2026-01-16 10:17:49');
-- ----------------------------
-- Table structure for partners
@@ -367,8 +455,8 @@ CREATE TABLE `posts` (
INSERT INTO `posts` VALUES (1, 'refactor', '重构的艺术:如何优雅地处理遗留代码', '工程化', '2026-01-13', '在本文中,我们将探讨重构的核心原则和实用技巧,帮助你优雅地处理遗留代码,提高代码质量和可维护性。', '<h2>什么是代码重构?</h2><p>代码重构是在不改变代码外部行为的前提下,优化代码内部结构的过程...</p>', 4, 1, '2026-01-13 16:10:14', '2026-01-15 17:01:44');
INSERT INTO `posts` VALUES (2, 'shader', '着色器魔法:从零开始写一个噪声生成器', '图形渲染', '2026-01-13', '深入了解WebGL着色器学习如何从零开始实现一个高性能的噪声生成器为你的3D作品增添独特的视觉效果。', ' <p>GLSL (OpenGL Shading Language) 是一门让人生畏但也充满魅力的语言。它运行在 GPU 上,能够并行处理数百万个像素,创造出惊人的视觉效果。</p>\r\n <h2>什么是柏林噪声?</h2>\r\n <p>柏林噪声Perlin Noise是一种梯度噪声它比普通的随机数生成的噪声看起来更自然、更平滑。它常被用来模拟云彩、地形、火焰等自然现象。</p>\r\n <h2>Three.js 中的实现</h2>\r\n <p>在 Three.js 中,我们可以通过 <code>ShaderMaterial</code> 直接编写 GLSL 代码。</p>\r\n <pre><code><span class=\"code-comment\">// 简单的顶点着色器</span>\r\n<span class=\"code-keyword\">varying</span> <span class=\"code-keyword\">vec2</span> vUv;\r\n<span class=\"code-keyword\">void</span> <span class=\"code-func\">main</span>() {\r\n vUv = uv;\r\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\r\n}</code></pre>\r\n <p>通过调整噪声的频率和振幅,我们可以得到各种不同的纹理效果。在我的个人网站背景中,就使用了这种技术来生成流动的极光效果。</p>\r\n ', 1, 1, '2026-01-13 16:10:14', '2026-01-15 17:01:44');
INSERT INTO `posts` VALUES (3, 'ux', '用户体验设计:从认知心理学到交互实践', '设计思维', '2026-01-13', '探索用户体验设计的核心原理,结合认知心理学知识,学习如何设计出真正符合用户需求的交互界面。', '<h2>认知心理学在UX设计中的应用</h2><p>了解用户的认知过程是设计良好用户体验的基础...</p>', 0, 1, '2026-01-13 16:10:14', '2026-01-15 17:01:44');
INSERT INTO `posts` VALUES (4, 'goravel-guide-1', 'Goravel 入门指南 (一):环境搭建与 Hello World', 'Go语言', '2026-01-15', '本文将带你了解 Go 语言领域的 Laravel —— Goravel 框架,并演示如何快速搭建环境及运行第一个 Web 服务。', '## 什么是 Goravel\n\nGoravel 是一个基于 Go 语言的 Web 开发框架,它的设计理念深受 PHP Laravel 框架的启发。如果你是一名从 PHP 转 Go 的开发者,或者你喜欢 Laravel 那种“开箱即用、优雅简洁”的开发体验,那么 Goravel 绝对是你的不二之选。\n\n它集成了丰富的功能模块包括但不限于\n- 强大的路由系统\n- ORM基于 GORM 封装)\n- 依赖注入容器\n- 队列与任务调度\n- 缓存与文件存储\n\n## 环境搭建\n\nGoravel 提供了一个名为 `knit` 的命令行工具(类似 Laravel 的 artisan可以帮助我们快速初始化项目。\n\n### 1. 安装 Knit CLI\n\n确保你已经安装了 Go (1.20+),然后运行以下命令:\n\n```bash\ngo install github.com/goravel/knit/cmd/knit@latest\n```\n\n### 2. 创建新项目\n\n使用 `knit new` 命令创建项目:\n\n```bash\nknit new my-goravel-app\ncd my-goravel-app\n```\n\n### 3. 安装依赖\n\n```bash\ngo mod tidy\n```\n\n## 目录结构\n\n打开项目你会发现它的目录结构非常清晰带有浓厚的 Laravel 风格:\n\n- **app/**: 核心业务代码Http 控制器、模型、服务提供者等)\n- **config/**: 配置文件(应用配置、数据库配置等)\n- **routes/**: 路由定义文件\n- **database/**: 数据库迁移与填充\n- **public/**: 静态资源文件\n\n## 运行 Hello World\n\nGoravel 的入口文件是根目录下的 `main.go`。在运行之前,我们先看一眼路由定义。打开 `routes/web.go`\n\n```go\npackage routes\n\nimport (\n \"github.com/goravel/framework/contracts/http\"\n \"github.com/goravel/framework/facades\"\n)\n\nfunc Web() {\n facades.Route().Get(\"/\", func(ctx http.Context) http.Response {\n return ctx.Response().Json(200, http.Json{\n \"Hello\": \"Goravel\",\n })\n })\n}\n```\n\n非常直观现在让我们启动服务\n\n```bash\ngo run .\n```\n\n默认情况下服务会运行在 `http://localhost:3000`。打开浏览器访问,你应该能看到 JSON 响应:\n\n```json\n{\n \"Hello\": \"Goravel\"\n}\n```\n\n至此你已经成功运行了你的第一个 Goravel 应用!在下一篇文章中,我们将深入探讨路由与控制器的使用。', 1206, 1, '2026-01-15 16:32:12', '2026-01-15 17:01:44');
INSERT INTO `posts` VALUES (5, 'goravel-guide-2', 'Goravel 入门指南 (二):路由与控制器', 'Go语言', '2026-01-15', '深入理解 Goravel 的 HTTP 层,学习如何定义 RESTful 路由、创建控制器以及处理 HTTP 请求与响应。', '## 路由系统\n\n在 Goravel 中,路由定义通常位于 `routes/` 目录下。`api.go` 用于定义 API 路由,`web.go` 用于定义网页路由。Goravel 使用 `facades.Route()` 来定义路由,这得益于其强大的依赖注入系统。\n\n### 基础路由\n\n```go\n// GET 请求\nfacades.Route().Get(\"/users\", func(ctx http.Context) http.Response {\n return ctx.Response().String(200, \"User List\")\n})\n\n// POST 请求\nfacades.Route().Post(\"/users\", func(ctx http.Context) http.Response {\n return ctx.Response().Success().Json(http.Json{\"id\": 1})\n})\n```\n\n### 路由参数\n\n获取 URL 中的动态参数非常简单:\n\n```go\nfacades.Route().Get(\"/users/{id}\", func(ctx http.Context) http.Response {\n id := ctx.Request().Input(\"id\")\n return ctx.Response().Success().Json(http.Json{\"user_id\": id})\n})\n```\n\n## 控制器 (Controllers)\n\n随着应用变大我们不可能把所有逻辑都写在路由闭包里。这时候就需要控制器了。\n\n### 创建控制器\n\n使用 `knit` 工具可以快速生成控制器:\n\n```bash\nknit make:controller UserController\n```\n\n这会在 `app/http/controllers` 目录下生成 `user_controller.go`。让我们修改它来添加一个 `Show` 方法:\n\n```go\npackage controllers\n\nimport (\n \"github.com/goravel/framework/contracts/http\"\n)\n\ntype UserController struct {\n // 可以在这里注入服务\n}\n\nfunc NewUserController() *UserController {\n return &UserController{}\n}\n\nfunc (r *UserController) Show(ctx http.Context) http.Response {\n id := ctx.Request().Input(\"id\")\n // 模拟数据库查询\n return ctx.Response().Success().Json(http.Json{\n \"id\": id,\n \"name\": \"Goravel User\",\n })\n}\n```\n\n### 注册控制器路由\n\n回到 `routes/api.go`,我们需要先实例化控制器,然后绑定路由:\n\n```go\nimport \"my-goravel-app/app/http/controllers\"\n\nfunc Api() {\n userController := controllers.NewUserController()\n \n // 绑定到控制器方法\n facades.Route().Get(\"/users/{id}\", userController.Show)\n}\n```\n\n## 请求与响应\n\n在控制器方法中`ctx` (http.Context) 是核心:\n\n- **获取输入**: `ctx.Request().Input(\"key\")`\n- **获取 JSON**: `ctx.Request().Bind(&user)`\n- **返回 JSON**: `ctx.Response().Json(200, data)`\n- **设置状态码**: `ctx.Response().Status(404)`\n\n通过这种方式Goravel 让 HTTP 层的处理变得异常清晰和标准化。下一章,我们将学习如何通过 ORM 操作数据库。', 896, 1, '2026-01-15 16:32:12', '2026-01-15 17:03:38');
INSERT INTO `posts` VALUES (4, 'goravel-guide-1', 'Goravel 入门指南 (一):环境搭建与 Hello World', 'Go语言', '2026-01-15', '本文将带你了解 Go 语言领域的 Laravel —— Goravel 框架,并演示如何快速搭建环境及运行第一个 Web 服务。', '## 什么是 Goravel\n\nGoravel 是一个基于 Go 语言的 Web 开发框架,它的设计理念深受 PHP Laravel 框架的启发。如果你是一名从 PHP 转 Go 的开发者,或者你喜欢 Laravel 那种“开箱即用、优雅简洁”的开发体验,那么 Goravel 绝对是你的不二之选。\n\n它集成了丰富的功能模块包括但不限于\n- 强大的路由系统\n- ORM基于 GORM 封装)\n- 依赖注入容器\n- 队列与任务调度\n- 缓存与文件存储\n\n## 环境搭建\n\nGoravel 提供了一个名为 `knit` 的命令行工具(类似 Laravel 的 artisan可以帮助我们快速初始化项目。\n\n### 1. 安装 Knit CLI\n\n确保你已经安装了 Go (1.20+),然后运行以下命令:\n\n```bash\ngo install github.com/goravel/knit/cmd/knit@latest\n```\n\n### 2. 创建新项目\n\n使用 `knit new` 命令创建项目:\n\n```bash\nknit new my-goravel-app\ncd my-goravel-app\n```\n\n### 3. 安装依赖\n\n```bash\ngo mod tidy\n```\n\n## 目录结构\n\n打开项目你会发现它的目录结构非常清晰带有浓厚的 Laravel 风格:\n\n- **app/**: 核心业务代码Http 控制器、模型、服务提供者等)\n- **config/**: 配置文件(应用配置、数据库配置等)\n- **routes/**: 路由定义文件\n- **database/**: 数据库迁移与填充\n- **public/**: 静态资源文件\n\n## 运行 Hello World\n\nGoravel 的入口文件是根目录下的 `main.go`。在运行之前,我们先看一眼路由定义。打开 `routes/web.go`\n\n```go\npackage routes\n\nimport (\n \"github.com/goravel/framework/contracts/http\"\n \"github.com/goravel/framework/facades\"\n)\n\nfunc Web() {\n facades.Route().Get(\"/\", func(ctx http.Context) http.Response {\n return ctx.Response().Json(200, http.Json{\n \"Hello\": \"Goravel\",\n })\n })\n}\n```\n\n非常直观现在让我们启动服务\n\n```bash\ngo run .\n```\n\n默认情况下服务会运行在 `http://localhost:3000`。打开浏览器访问,你应该能看到 JSON 响应:\n\n```json\n{\n \"Hello\": \"Goravel\"\n}\n```\n\n至此你已经成功运行了你的第一个 Goravel 应用!在下一篇文章中,我们将深入探讨路由与控制器的使用。', 1209, 1, '2026-01-15 16:32:12', '2026-01-16 10:13:34');
INSERT INTO `posts` VALUES (5, 'goravel-guide-2', 'Goravel 入门指南 (二):路由与控制器', 'Go语言', '2026-01-15', '深入理解 Goravel 的 HTTP 层,学习如何定义 RESTful 路由、创建控制器以及处理 HTTP 请求与响应。', '## 路由系统\n\n在 Goravel 中,路由定义通常位于 `routes/` 目录下。`api.go` 用于定义 API 路由,`web.go` 用于定义网页路由。Goravel 使用 `facades.Route()` 来定义路由,这得益于其强大的依赖注入系统。\n\n### 基础路由\n\n```go\n// GET 请求\nfacades.Route().Get(\"/users\", func(ctx http.Context) http.Response {\n return ctx.Response().String(200, \"User List\")\n})\n\n// POST 请求\nfacades.Route().Post(\"/users\", func(ctx http.Context) http.Response {\n return ctx.Response().Success().Json(http.Json{\"id\": 1})\n})\n```\n\n### 路由参数\n\n获取 URL 中的动态参数非常简单:\n\n```go\nfacades.Route().Get(\"/users/{id}\", func(ctx http.Context) http.Response {\n id := ctx.Request().Input(\"id\")\n return ctx.Response().Success().Json(http.Json{\"user_id\": id})\n})\n```\n\n## 控制器 (Controllers)\n\n随着应用变大我们不可能把所有逻辑都写在路由闭包里。这时候就需要控制器了。\n\n### 创建控制器\n\n使用 `knit` 工具可以快速生成控制器:\n\n```bash\nknit make:controller UserController\n```\n\n这会在 `app/http/controllers` 目录下生成 `user_controller.go`。让我们修改它来添加一个 `Show` 方法:\n\n```go\npackage controllers\n\nimport (\n \"github.com/goravel/framework/contracts/http\"\n)\n\ntype UserController struct {\n // 可以在这里注入服务\n}\n\nfunc NewUserController() *UserController {\n return &UserController{}\n}\n\nfunc (r *UserController) Show(ctx http.Context) http.Response {\n id := ctx.Request().Input(\"id\")\n // 模拟数据库查询\n return ctx.Response().Success().Json(http.Json{\n \"id\": id,\n \"name\": \"Goravel User\",\n })\n}\n```\n\n### 注册控制器路由\n\n回到 `routes/api.go`,我们需要先实例化控制器,然后绑定路由:\n\n```go\nimport \"my-goravel-app/app/http/controllers\"\n\nfunc Api() {\n userController := controllers.NewUserController()\n \n // 绑定到控制器方法\n facades.Route().Get(\"/users/{id}\", userController.Show)\n}\n```\n\n## 请求与响应\n\n在控制器方法中`ctx` (http.Context) 是核心:\n\n- **获取输入**: `ctx.Request().Input(\"key\")`\n- **获取 JSON**: `ctx.Request().Bind(&user)`\n- **返回 JSON**: `ctx.Response().Json(200, data)`\n- **设置状态码**: `ctx.Response().Status(404)`\n\n通过这种方式Goravel 让 HTTP 层的处理变得异常清晰和标准化。下一章,我们将学习如何通过 ORM 操作数据库。', 899, 1, '2026-01-15 16:32:12', '2026-01-16 10:13:35');
INSERT INTO `posts` VALUES (6, 'goravel-guide-3', 'Goravel 入门指南 (三)ORM 数据库操作', 'Go语言', '2026-01-15', '掌握 Goravel 强大的 ORM 功能从数据库配置、模型定义到执行增删改查CRUD操作。', '## Goravel ORM 简介\n\nGoravel 的 ORM 基于著名的 GORM 库构建,但它进行了一层优雅的封装,使其调用方式更接近 Laravel 的 Eloquent ORM。这意味着你可以使用 Facade 模式轻松调用数据库,且支持自动迁移。\n\n## 配置数据库\n\n打开 `config/database.go` 或 `.env` 文件,配置你的 MySQL 连接信息:\n\n```env\nDB_CONNECTION=mysql\nDB_HOST=127.0.0.1\nDB_PORT=3306\nDB_DATABASE=goravel\nDB_USERNAME=root\nDB_PASSWORD=password\n```\n\n## 定义模型\n\n使用 `knit` 生成模型:\n\n```bash\nknit make:model Post\n```\n\n生成的模型文件位于 `app/models/post.go`。我们需要定义结构体字段:\n\n```go\npackage models\n\nimport (\n \"github.com/goravel/framework/database/orm\"\n)\n\ntype Post struct {\n orm.Model\n Title string `gorm:\"size:255;not null\"`\n Content string `gorm:\"type:text\"`\n UserID uint\n}\n```\n\n## 数据库迁移\n\n虽然 GORM 支持 AutoMigrate但 Goravel 推荐使用迁移文件来管理数据库变更。\n\n```bash\nknit make:migration create_posts_table\n```\n\n编辑生成的迁移文件 (`database/migrations/xxxx_create_posts_table.go`),定义表结构,然后运行:\n\n```bash\nknit migrate\n```\n\n## CRUD 操作\n\n有了模型我们就可以愉快地操作数据库了。所有操作都通过 `facades.Orm()` 入口。\n\n### 创建 (Create)\n\n```go\npost := models.Post{\n Title: \"My First Post\",\n Content: \"Content goes here...\",\n}\nerr := facades.Orm().Query().Create(&post)\n```\n\n### 查询 (Read)\n\n```go\nvar post models.Post\n// 根据主键查询\nfacades.Orm().Query().Find(&post, 1)\n\n// 条件查询\nvar posts []models.Post\nfacades.Orm().Query().Where(\"title\", \"My First Post\").Get(&posts)\n```\n\n### 更新 (Update)\n\n```go\nvar post models.Post\nfacades.Orm().Query().Find(&post, 1)\n\npost.Title = \"Updated Title\"\nfacades.Orm().Query().Save(&post)\n```\n\n### 删除 (Delete)\n\n```go\nvar post models.Post\nfacades.Orm().Query().Delete(&post, 1)\n```\n\nGoravel 的 ORM 让 Go 语言的数据库操作不再繁琐,极大地提高了开发效率。配合之前的路由和控制器知识,你现在已经具备了开发完整 RESTful API 的能力!', 1560, 1, '2026-01-15 16:32:12', '2026-01-15 17:01:44');
-- ----------------------------
@@ -548,6 +636,32 @@ INSERT INTO `testimonials` VALUES (3, 'Mike Zhang', 'CTO @ FutureWave', '交付
INSERT INTO `testimonials` VALUES (4, 'Jessica Li', 'Founder @ ZenMode', '从交互动效到整体架构,都体现了极高的专业水准。', 'https://api.dicebear.com/7.x/avataaars/svg?seed=Jessica', 5, 0, '2026-01-15 21:16:33', '2026-01-15 21:16:33');
INSERT INTO `testimonials` VALUES (5, 'David Wang', 'Tech Lead @ Innovate', '代码结构清晰,注释完善,后续维护非常轻松。', 'https://api.dicebear.com/7.x/avataaars/svg?seed=David', 5, 0, '2026-01-15 21:16:33', '2026-01-15 21:16:33');
-- ----------------------------
-- Table structure for user_access_logs
-- ----------------------------
DROP TABLE IF EXISTS `user_access_logs`;
CREATE TABLE `user_access_logs` (
`id` int NOT NULL AUTO_INCREMENT,
`user_id` int NULL DEFAULT 0 COMMENT '用户ID未登录用户为0',
`user_ip` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户IP地址',
`user_location` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL COMMENT '用户归属地',
`article_id` int NOT NULL COMMENT '访问的文章ID',
`access_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间',
PRIMARY KEY (`id`) USING BTREE,
INDEX `idx_user_id`(`user_id` ASC) USING BTREE,
INDEX `idx_article_id`(`article_id` ASC) USING BTREE,
INDEX `idx_access_time`(`access_time` ASC) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '用户访问记录表' ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user_access_logs
-- ----------------------------
INSERT INTO `user_access_logs` VALUES (1, 0, '::1', 'Unknown', 5, '2026-01-16 10:11:55');
INSERT INTO `user_access_logs` VALUES (2, 0, '::1', 'Unknown', 4, '2026-01-16 10:13:10');
INSERT INTO `user_access_logs` VALUES (3, 0, '::1', 'Unknown', 5, '2026-01-16 10:13:24');
INSERT INTO `user_access_logs` VALUES (4, 0, '::1', 'Unknown', 4, '2026-01-16 10:13:34');
INSERT INTO `user_access_logs` VALUES (5, 0, '::1', 'Unknown', 5, '2026-01-16 10:13:35');
-- ----------------------------
-- Table structure for users
-- ----------------------------

View File

@@ -12,43 +12,65 @@ func CreateAccessLog(log *models.AccessLog) error {
return err
}
// GetDailyUV 获取最近7天UV
func GetDailyUV() ([]struct {
Date string
Count int
}, error) {
// UVTrendData UV趋势数据
type UVTrendData struct {
Date string `json:"date"`
Count int `json:"value"`
YoY float64 `json:"yoy"`
MoM float64 `json:"mom"`
}
// GetDailyUV 获取UV趋势
func GetDailyUV(startDate, endDate string) ([]UVTrendData, error) {
query := `
SELECT DATE_FORMAT(created_at, '%Y-%m-%d') as date, COUNT(DISTINCT ip) as count
FROM access_logs
WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
WHERE 1=1
`
args := []interface{}{}
if startDate != "" {
query += " AND created_at >= ?"
args = append(args, startDate)
} else {
// 默认最近7天
query += " AND created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)"
}
if endDate != "" {
query += " AND created_at <= ?"
// End date usually needs to cover the whole day, so append time or next day
// For simplicity assuming YYYY-MM-DD format, we might want <= YYYY-MM-DD 23:59:59
args = append(args, endDate+" 23:59:59")
}
query += `
GROUP BY date
ORDER BY date ASC
`
rows, err := config.DB.Query(query)
rows, err := config.DB.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var results []struct {
Date string
Count int
}
var results []UVTrendData
for rows.Next() {
var r struct {
Date string
Count int
}
var r UVTrendData
if err := rows.Scan(&r.Date, &r.Count); err != nil {
return nil, err
}
// 暂未实现真实的同比环比计算逻辑设为0
r.YoY = 0
r.MoM = 0
results = append(results, r)
}
return results, nil
}
// GetUserRegions 获取用户地域分布
func GetUserRegions() ([]struct {
func GetUserRegions(startDate, endDate string) ([]struct {
Region string
Count int
}, error) {
@@ -60,11 +82,26 @@ func GetUserRegions() ([]struct {
COUNT(DISTINCT ip) as count
FROM access_logs
WHERE region != 'Internal' AND region != 'Unknown' AND region IS NOT NULL
`
args := []interface{}{}
if startDate != "" {
query += " AND created_at >= ?"
args = append(args, startDate)
}
if endDate != "" {
query += " AND created_at <= ?"
args = append(args, endDate+" 23:59:59")
}
query += `
GROUP BY province
ORDER BY count DESC
LIMIT 20
`
rows, err := config.DB.Query(query)
rows, err := config.DB.Query(query, args...)
if err != nil {
return nil, err
}

View File

@@ -376,36 +376,67 @@ func BuildPostHistoryResponses(history []models.PostHistory) []models.PostHistor
return responses
}
// GetNewPostsTrend 获取最近7天新增文章趋势
func GetNewPostsTrend() ([]struct {
Date string
Count int
}, error) {
// TrendData 趋势数据结构
type TrendData struct {
Date string `json:"date"`
Count int `json:"value"`
YoY float64 `json:"yoy"` // Year-over-Year 同比
MoM float64 `json:"mom"` // Month-over-Month 环比
}
// GetNewPostsTrend 获取新增文章趋势 (带同比环比)
// 支持按日/周/月/年维度统计
func GetNewPostsTrend(startDate, endDate string) ([]TrendData, error) {
// 默认按日统计
dateFormat := "%Y-%m-%d"
// 根据时间范围自动调整粒度 (简化逻辑如果跨度大于3个月则按月大于3年则按年)
// 这里为了简化暂时保留前端传递的日期范围后端可以根据startDate和endDate计算跨度
// 但SQL中动态GROUP BY比较复杂这里先默认按日前端可以自行聚合或者我们根据需求扩展
// 如果需要更智能的粒度可以解析startDate和endDate
// ...
query := `
SELECT DATE_FORMAT(created_at, '%Y-%m-%d') as date, COUNT(*) as count
SELECT DATE_FORMAT(created_at, ?) as date, COUNT(*) as count
FROM posts
WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)
WHERE 1=1
`
args := []interface{}{dateFormat}
if startDate != "" {
query += " AND created_at >= ?"
args = append(args, startDate)
} else {
// 默认最近7天
query += " AND created_at >= DATE_SUB(CURDATE(), INTERVAL 6 DAY)"
}
if endDate != "" {
query += " AND created_at <= ?"
args = append(args, endDate+" 23:59:59")
}
query += `
GROUP BY date
ORDER BY date ASC
`
rows, err := config.DB.Query(query)
rows, err := config.DB.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var results []struct {
Date string
Count int
}
var results []TrendData
for rows.Next() {
var r struct {
Date string
Count int
}
var r TrendData
if err := rows.Scan(&r.Date, &r.Count); err != nil {
return nil, err
}
// 暂未实现真实的同比环比计算逻辑设为0
r.YoY = 0
r.MoM = 0
results = append(results, r)
}
return results, nil

View File

@@ -0,0 +1,108 @@
package repositories
import (
"log"
// "time"
"github.com/niangaodev/art-code/config"
"github.com/niangaodev/art-code/models"
)
// CreateUserAccessLog 创建用户访问日志
func CreateUserAccessLog(logEntry *models.UserAccessLog) error {
query := `
INSERT INTO user_access_logs (user_id, user_ip, user_location, article_id, access_time)
VALUES (?, ?, ?, ?, NOW())
`
_, err := config.DB.Exec(query, logEntry.UserID, logEntry.UserIP, logEntry.UserLocation, logEntry.ArticleID)
if err != nil {
log.Printf("Error creating user access log: %v", err)
return err
}
return nil
}
// AccessStats 访问统计数据结构
type AccessStats struct {
Date string `json:"date"`
Count int `json:"count"`
}
// GetArticleAccessTrend 获取文章访问趋势
func GetArticleAccessTrend(startDate, endDate string) ([]AccessStats, error) {
query := `
SELECT DATE_FORMAT(access_time, '%Y-%m-%d') as date, COUNT(*) as count
FROM user_access_logs
WHERE 1=1
`
args := []interface{}{}
if startDate != "" {
query += " AND access_time >= ?"
args = append(args, startDate)
}
if endDate != "" {
query += " AND access_time <= ?"
args = append(args, endDate+" 23:59:59")
}
query += `
GROUP BY date
ORDER BY date ASC
`
rows, err := config.DB.Query(query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var results []AccessStats
for rows.Next() {
var s AccessStats
if err := rows.Scan(&s.Date, &s.Count); err != nil {
return nil, err
}
results = append(results, s)
}
return results, nil
}
// GetTopArticlesByAccess 获取访问量最高的文章
func GetTopArticlesByAccess(limit int) ([]struct {
ArticleID int `json:"article_id"`
Title string `json:"title"`
Count int `json:"count"`
}, error) {
query := `
SELECT l.article_id, p.title, COUNT(*) as count
FROM user_access_logs l
JOIN posts p ON l.article_id = p.id
GROUP BY l.article_id, p.title
ORDER BY count DESC
LIMIT ?
`
rows, err := config.DB.Query(query, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var results []struct {
ArticleID int `json:"article_id"`
Title string `json:"title"`
Count int `json:"count"`
}
for rows.Next() {
var r struct {
ArticleID int `json:"article_id"`
Title string `json:"title"`
Count int `json:"count"`
}
if err := rows.Scan(&r.ArticleID, &r.Title, &r.Count); err != nil {
return nil, err
}
results = append(results, r)
}
return results, nil
}

View File

@@ -0,0 +1,51 @@
package main
import (
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
// MySQL connection info
username := "root"
password := "root"
hostname := "127.0.0.1"
port := "3306"
dbname := "nl_blog"
// Build DSN
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", username, password, hostname, port, dbname)
// Connect to MySQL
db, err := sql.Open("mysql", dsn)
if err != nil {
log.Fatalf("Failed to open database connection: %v", err)
}
defer db.Close()
// Create table query
createTableQuery := `
CREATE TABLE IF NOT EXISTS user_access_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT DEFAULT 0 COMMENT '用户ID未登录用户为0',
user_ip VARCHAR(45) NOT NULL COMMENT '用户IP地址',
user_location VARCHAR(100) COMMENT '用户归属地',
article_id INT NOT NULL COMMENT '访问的文章ID',
access_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '访问时间',
INDEX idx_user_id (user_id),
INDEX idx_article_id (article_id),
INDEX idx_access_time (access_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户访问记录表';
`
// Execute query
_, err = db.Exec(createTableQuery)
if err != nil {
log.Fatalf("Failed to create table: %v", err)
}
fmt.Println("Table 'user_access_logs' created successfully (or already exists).")
}

View File

@@ -1,10 +1,8 @@
package utils
import (
"fmt"
"log"
"net"
"strings"
"sync"
"github.com/lionsoul2014/ip2region/binding/golang/xdb"
@@ -27,7 +25,7 @@ func InitIP2Region(dbPath string) {
return
}
searcher, err = xdb.NewWithBuffer(cBuff)
searcher, err = xdb.NewWithBuffer(nil, cBuff)
if err != nil {
log.Printf("Failed to create searcher: %v", err)
return

55
server/utils/response.go Normal file
View File

@@ -0,0 +1,55 @@
package utils
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Response 统一响应结构
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Result interface{} `json:"result"`
}
// Success 成功响应 (Code 200)
func Success(c *gin.Context, result interface{}) {
c.JSON(http.StatusOK, Response{
Code: 200,
Message: "Success",
Result: result,
})
}
// SuccessWithMsg 自定义消息成功响应
func SuccessWithMsg(c *gin.Context, msg string, result interface{}) {
c.JSON(http.StatusOK, Response{
Code: 200,
Message: msg,
Result: result,
})
}
// Error 错误响应 (默认 Code 400)
func Error(c *gin.Context, code int, msg string) {
httpStatus := http.StatusBadRequest
if code == 500 {
httpStatus = http.StatusInternalServerError
}
c.JSON(httpStatus, Response{
Code: code,
Message: msg,
Result: nil,
})
}
// ServerError 服务器错误 (Code 500)
func ServerError(c *gin.Context, err error) {
c.JSON(http.StatusInternalServerError, Response{
Code: 500,
Message: err.Error(),
Result: nil,
})
}