初始化
This commit is contained in:
@@ -3,7 +3,31 @@
|
||||
<div class="max-w-4xl mx-auto pt-32 px-6 pb-20">
|
||||
<div class="mb-16 text-center">
|
||||
<h2 class="font-serif text-5xl italic text-white mb-6">深度思考</h2>
|
||||
<p class="text-art-muted max-w-lg mx-auto">关于前端技术、交互设计以及数字艺术的深度思考。</p>
|
||||
<p class="text-art-muted max-w-lg mx-auto mb-8">关于前端技术、交互设计以及数字艺术的深度思考。</p>
|
||||
|
||||
<!-- Search UI -->
|
||||
<div class="max-w-md mx-auto relative">
|
||||
<input
|
||||
type="text"
|
||||
v-model="searchQuery"
|
||||
@keyup.enter="handleSearch"
|
||||
placeholder="搜索文章标题或内容..."
|
||||
class="w-full bg-white/5 border border-white/10 rounded-full px-6 py-3 text-white placeholder-white/30 focus:outline-none focus:border-art-accent transition-colors"
|
||||
/>
|
||||
<button
|
||||
v-if="searchQuery"
|
||||
@click="clearSearch"
|
||||
class="absolute right-12 top-1/2 -translate-y-1/2 text-white/30 hover:text-white transition-colors"
|
||||
>
|
||||
<i data-lucide="x" class="w-4 h-4"></i>
|
||||
</button>
|
||||
<button
|
||||
@click="handleSearch"
|
||||
class="absolute right-4 top-1/2 -translate-y-1/2 text-white/50 hover:text-art-accent transition-colors"
|
||||
>
|
||||
<i data-lucide="search" class="w-5 h-5"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Loading state -->
|
||||
@@ -19,6 +43,14 @@
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Empty state -->
|
||||
<div v-else-if="blogPosts.length === 0" class="text-center py-20 text-art-muted">
|
||||
<p>没有找到相关文章</p>
|
||||
<button v-if="isSearching" @click="clearSearch" class="mt-4 text-art-accent hover:underline">
|
||||
清除搜索条件
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Blog posts list -->
|
||||
<div v-else class="space-y-12" id="blog-list-container">
|
||||
<!-- Blog posts will be rendered here -->
|
||||
@@ -34,11 +66,9 @@
|
||||
<span class="text-sm text-art-muted">{{ post.date }}</span>
|
||||
</div>
|
||||
<div class="md:w-3/4 space-y-4">
|
||||
<h3 class="font-serif text-3xl text-white group-hover:text-art-accent transition-colors leading-tight">
|
||||
{{ post.title }}
|
||||
<h3 class="font-serif text-3xl text-white group-hover:text-art-accent transition-colors leading-tight" v-html="highlightText(post.title)">
|
||||
</h3>
|
||||
<p class="text-art-muted font-light leading-relaxed">
|
||||
{{ post.excerpt }}
|
||||
<p class="text-art-muted font-light leading-relaxed" v-html="highlightText(post.excerpt)">
|
||||
</p>
|
||||
<div class="text-xs text-art-accent font-medium mt-4 group-hover:text-white transition-colors">阅读全文 -></div>
|
||||
</div>
|
||||
@@ -50,24 +80,34 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onBeforeMount } from 'vue'
|
||||
import { ref, onMounted, nextTick } from 'vue'
|
||||
import { fetchPosts, Post } from '../services/api'
|
||||
import { useScrollAnimation } from '../composables/useScrollAnimation'
|
||||
|
||||
const blogPosts = ref<Post[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const searchQuery = ref('')
|
||||
const isSearching = ref(false)
|
||||
|
||||
const { initObserver } = useScrollAnimation()
|
||||
|
||||
const fetchBlogPosts = async () => {
|
||||
const refreshIcons = () => {
|
||||
if ((window as any).lucide) {
|
||||
(window as any).lucide.createIcons()
|
||||
}
|
||||
}
|
||||
|
||||
const fetchBlogPosts = async (query?: string) => {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const posts = await fetchPosts()
|
||||
const posts = await fetchPosts(query)
|
||||
blogPosts.value = posts
|
||||
// 初始化动画 - 在数据加载完成后
|
||||
initObserver()
|
||||
nextTick(() => {
|
||||
initObserver()
|
||||
refreshIcons()
|
||||
})
|
||||
} catch (err) {
|
||||
console.error('Error fetching blog posts:', err)
|
||||
error.value = '获取博客文章失败,请稍后重试'
|
||||
@@ -76,11 +116,28 @@ const fetchBlogPosts = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const handleSearch = () => {
|
||||
if (!searchQuery.value.trim() && !isSearching.value) return
|
||||
isSearching.value = !!searchQuery.value.trim()
|
||||
fetchBlogPosts(searchQuery.value)
|
||||
}
|
||||
|
||||
const clearSearch = () => {
|
||||
searchQuery.value = ''
|
||||
isSearching.value = false
|
||||
fetchBlogPosts()
|
||||
}
|
||||
|
||||
const highlightText = (text: string | undefined) => {
|
||||
if (!text) return ''
|
||||
if (!isSearching.value || !searchQuery.value) return text
|
||||
|
||||
const regex = new RegExp(`(${searchQuery.value})`, 'gi')
|
||||
return text.replace(regex, '<span class="text-art-accent bg-art-accent/10 font-bold">$1</span>')
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
fetchBlogPosts()
|
||||
// 初始化Lucide图标
|
||||
if (window.lucide) {
|
||||
window.lucide.createIcons()
|
||||
}
|
||||
refreshIcons()
|
||||
})
|
||||
</script>
|
||||
@@ -125,7 +125,7 @@ const activeId = ref<string>('')
|
||||
const observer = ref<IntersectionObserver | null>(null)
|
||||
|
||||
const post = ref<Post>({
|
||||
id: postId,
|
||||
id: Number(postId) || 0,
|
||||
title: '',
|
||||
category: '',
|
||||
date: '',
|
||||
|
||||
@@ -69,7 +69,7 @@ const fetchPosts = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const deletePost = async (id: string) => {
|
||||
const deletePost = async (id: number) => {
|
||||
if (confirm('确定要删除这篇文章吗?')) {
|
||||
try {
|
||||
await deletePostApi(id)
|
||||
|
||||
@@ -56,7 +56,7 @@ export interface Work {
|
||||
|
||||
// 文章相关类型
|
||||
export interface Post {
|
||||
id: string
|
||||
id: number
|
||||
title: string
|
||||
category: string
|
||||
date: string
|
||||
@@ -67,7 +67,7 @@ export interface Post {
|
||||
|
||||
export interface PostHistory {
|
||||
id: number
|
||||
postId: string
|
||||
postId: number
|
||||
version: number
|
||||
title: string
|
||||
category: string
|
||||
@@ -425,9 +425,13 @@ export const getAdminPosts = async (): Promise<Post[]> => {
|
||||
}
|
||||
}
|
||||
|
||||
export const fetchPosts = async (): Promise<Post[]> => {
|
||||
export const fetchPosts = async (query?: string): Promise<Post[]> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/posts`)
|
||||
let url = `${API_BASE}/posts`
|
||||
if (query) {
|
||||
url += `?q=${encodeURIComponent(query)}`
|
||||
}
|
||||
const response = await fetch(url)
|
||||
if (!response.ok) throw new Error('Failed to fetch posts')
|
||||
return await response.json()
|
||||
} catch (error) {
|
||||
@@ -436,7 +440,7 @@ export const fetchPosts = async (): Promise<Post[]> => {
|
||||
}
|
||||
}
|
||||
|
||||
export const fetchPost = async (id: string): Promise<Post> => {
|
||||
export const fetchPost = async (id: number | string): Promise<Post> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/posts/${id}`)
|
||||
if (!response.ok) throw new Error('Failed to fetch post')
|
||||
@@ -444,7 +448,7 @@ export const fetchPost = async (id: string): Promise<Post> => {
|
||||
} catch (error) {
|
||||
console.error(`Error fetching post ${id}:`, error)
|
||||
return {
|
||||
id: id,
|
||||
id: Number(id),
|
||||
title: '默认文章',
|
||||
category: '默认分类',
|
||||
date: '2024-01-01'
|
||||
@@ -469,7 +473,7 @@ export const createPost = async (postData: Omit<Post, 'id'>): Promise<void> => {
|
||||
}
|
||||
}
|
||||
|
||||
export const updatePost = async (id: string, postData: Omit<Post, 'id'>): Promise<void> => {
|
||||
export const updatePost = async (id: number | string, postData: Omit<Post, 'id'>): Promise<void> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/posts/${id}`, {
|
||||
method: 'PUT',
|
||||
@@ -486,7 +490,7 @@ export const updatePost = async (id: string, postData: Omit<Post, 'id'>): Promis
|
||||
}
|
||||
}
|
||||
|
||||
export const deletePost = async (id: string): Promise<void> => {
|
||||
export const deletePost = async (id: number | string): Promise<void> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/posts/${id}`, {
|
||||
method: 'DELETE',
|
||||
@@ -503,7 +507,7 @@ export const deletePost = async (id: string): Promise<void> => {
|
||||
}
|
||||
|
||||
// 文章历史记录API
|
||||
export const getPostHistory = async (postId: string): Promise<PostHistory[]> => {
|
||||
export const getPostHistory = async (postId: number | string): Promise<PostHistory[]> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/posts/${postId}/history`, {
|
||||
headers: getAuthHeaders()
|
||||
@@ -519,7 +523,7 @@ export const getPostHistory = async (postId: string): Promise<PostHistory[]> =>
|
||||
}
|
||||
}
|
||||
|
||||
export const getPostHistoryByVersion = async (postId: string, version: number): Promise<PostHistory> => {
|
||||
export const getPostHistoryByVersion = async (postId: number | string, version: number): Promise<PostHistory> => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/admin/posts/${postId}/history/${version}`, {
|
||||
headers: getAuthHeaders()
|
||||
|
||||
@@ -12,8 +12,11 @@ import (
|
||||
|
||||
// 获取博客文章列表
|
||||
func GetPosts(c *gin.Context) {
|
||||
// 获取查询参数
|
||||
keyword := c.Query("q")
|
||||
|
||||
// 从数据库获取所有博客文章
|
||||
posts, err := repositories.GetPosts()
|
||||
posts, err := repositories.GetPosts(keyword)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch posts"})
|
||||
return
|
||||
@@ -26,7 +29,14 @@ func GetPosts(c *gin.Context) {
|
||||
}
|
||||
|
||||
func GetPost(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
idStr := c.Param("id")
|
||||
// 转换ID
|
||||
var id uint
|
||||
if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
|
||||
return
|
||||
}
|
||||
|
||||
// 从数据库获取博客文章
|
||||
post, err := repositories.GetPostByID(id)
|
||||
if err != nil {
|
||||
@@ -104,7 +114,13 @@ func AdminCreatePost(c *gin.Context) {
|
||||
|
||||
// 更新文章
|
||||
func AdminUpdatePost(c *gin.Context) {
|
||||
postID := c.Param("id")
|
||||
postIDStr := c.Param("id")
|
||||
var postID uint
|
||||
if _, err := fmt.Sscanf(postIDStr, "%d", &postID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
|
||||
return
|
||||
}
|
||||
|
||||
var post models.Post
|
||||
if err := c.ShouldBindJSON(&post); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
||||
@@ -131,7 +147,12 @@ func AdminUpdatePost(c *gin.Context) {
|
||||
|
||||
// 删除文章
|
||||
func AdminDeletePost(c *gin.Context) {
|
||||
postID := c.Param("id")
|
||||
postIDStr := c.Param("id")
|
||||
var postID uint
|
||||
if _, err := fmt.Sscanf(postIDStr, "%d", &postID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
|
||||
return
|
||||
}
|
||||
|
||||
// 删除文章
|
||||
if err := repositories.DeletePost(postID); err != nil {
|
||||
@@ -144,7 +165,13 @@ func AdminDeletePost(c *gin.Context) {
|
||||
|
||||
// 获取文章历史记录
|
||||
func AdminGetPostHistory(c *gin.Context) {
|
||||
postID := c.Param("id")
|
||||
postIDStr := c.Param("id")
|
||||
var postID uint
|
||||
if _, err := fmt.Sscanf(postIDStr, "%d", &postID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
|
||||
return
|
||||
}
|
||||
|
||||
history, err := repositories.GetPostHistory(postID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get post history"})
|
||||
@@ -156,7 +183,13 @@ func AdminGetPostHistory(c *gin.Context) {
|
||||
|
||||
// 获取指定版本的文章历史记录
|
||||
func AdminGetPostHistoryByVersion(c *gin.Context) {
|
||||
postID := c.Param("id")
|
||||
postIDStr := c.Param("id")
|
||||
var postID uint
|
||||
if _, err := fmt.Sscanf(postIDStr, "%d", &postID); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid post ID"})
|
||||
return
|
||||
}
|
||||
|
||||
version := c.Param("version")
|
||||
|
||||
// 转换版本号为uint
|
||||
|
||||
@@ -6,21 +6,23 @@ import (
|
||||
|
||||
// Post 博客文章模型
|
||||
type Post struct {
|
||||
ID string `json:"id"`
|
||||
ID uint `json:"id"`
|
||||
OriginalID string `json:"originalId,omitempty"` // For backward compatibility
|
||||
Title string `json:"title"`
|
||||
Category string `json:"category"`
|
||||
Date time.Time `json:"date"`
|
||||
Date string `json:"date"` // YYYY-MM-DD
|
||||
Excerpt string `json:"excerpt"`
|
||||
Content string `json:"content"`
|
||||
ReadCount uint `json:"readCount"`
|
||||
IsPublished int `json:"isPublished"`
|
||||
IsPublished int `json:"isPublished"` // 0: draft, 1: published
|
||||
Tags []Tag `json:"tags"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
// PostResponse 博客文章响应模型
|
||||
type PostResponse struct {
|
||||
ID string `json:"id"`
|
||||
ID uint `json:"id"`
|
||||
Title string `json:"title"`
|
||||
Category string `json:"category"`
|
||||
Date string `json:"date"`
|
||||
@@ -47,11 +49,11 @@ type PostTag struct {
|
||||
// PostHistory 文章历史记录模型
|
||||
type PostHistory struct {
|
||||
ID uint `json:"id"`
|
||||
PostID string `json:"postId"`
|
||||
Version uint `json:"version"`
|
||||
PostID uint `json:"postId"`
|
||||
Version int `json:"version"`
|
||||
Title string `json:"title"`
|
||||
Category string `json:"category"`
|
||||
Date time.Time `json:"date"`
|
||||
Date string `json:"date"`
|
||||
Excerpt string `json:"excerpt"`
|
||||
Content string `json:"content"`
|
||||
IsPublished int `json:"isPublished"`
|
||||
@@ -63,8 +65,8 @@ type PostHistory struct {
|
||||
// PostHistoryResponse 文章历史记录响应模型
|
||||
type PostHistoryResponse struct {
|
||||
ID uint `json:"id"`
|
||||
PostID string `json:"postId"`
|
||||
Version uint `json:"version"`
|
||||
PostID uint `json:"postId"`
|
||||
Version int `json:"version"`
|
||||
Title string `json:"title"`
|
||||
Category string `json:"category"`
|
||||
Date string `json:"date"`
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
Target Server Version : 80407 (8.4.7)
|
||||
File Encoding : 65001
|
||||
|
||||
Date: 15/01/2026 16:53:22
|
||||
Date: 15/01/2026 17:03:48
|
||||
*/
|
||||
|
||||
SET NAMES utf8mb4;
|
||||
@@ -270,12 +270,12 @@ CREATE TABLE `posts` (
|
||||
-- ----------------------------
|
||||
-- Records of posts
|
||||
-- ----------------------------
|
||||
INSERT INTO `posts` VALUES (1, 'refactor', '重构的艺术:如何优雅地处理遗留代码', '工程化', '2026-01-12', '在本文中,我们将探讨重构的核心原则和实用技巧,帮助你优雅地处理遗留代码,提高代码质量和可维护性。', '<h2>什么是代码重构?</h2><p>代码重构是在不改变代码外部行为的前提下,优化代码内部结构的过程...</p>', 3, 1, '2026-01-13 16:10:14', '2026-01-15 16:16:57');
|
||||
INSERT INTO `posts` VALUES (2, 'shader', '着色器魔法:从零开始写一个噪声生成器', '图形渲染', '2025-12-08', '深入了解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 15:03:42');
|
||||
INSERT INTO `posts` VALUES (3, 'ux', '用户体验设计:从认知心理学到交互实践', '设计思维', '2025-11-20', '探索用户体验设计的核心原理,结合认知心理学知识,学习如何设计出真正符合用户需求的交互界面。', '<h2>认知心理学在UX设计中的应用</h2><p>了解用户的认知过程是设计良好用户体验的基础...</p>', 0, 1, '2026-01-13 16:10:14', '2026-01-13 16:10:14');
|
||||
INSERT INTO `posts` VALUES (4, 'goravel-guide-1', 'Goravel 入门指南 (一):环境搭建与 Hello World', 'Go语言', '2025-10-25', '本文将带你了解 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 16:32:27');
|
||||
INSERT INTO `posts` VALUES (5, 'goravel-guide-2', 'Goravel 入门指南 (二):路由与控制器', 'Go语言', '2025-10-26', '深入理解 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 操作数据库。', 894, 1, '2026-01-15 16:32:12', '2026-01-15 16:40:58');
|
||||
INSERT INTO `posts` VALUES (6, 'goravel-guide-3', 'Goravel 入门指南 (三):ORM 数据库操作', 'Go语言', '2025-10-27', '掌握 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 16:32:12');
|
||||
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 (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');
|
||||
|
||||
-- ----------------------------
|
||||
-- Table structure for role_permissions
|
||||
|
||||
@@ -8,10 +8,31 @@ import (
|
||||
"github.com/niangaodev/art-code/models"
|
||||
)
|
||||
|
||||
// GetPosts 获取所有博客文章
|
||||
func GetPosts() ([]models.Post, error) {
|
||||
query := "SELECT id, title, category, date, excerpt, content, read_count, is_published, created_at, updated_at FROM posts WHERE is_published = 1 ORDER BY date DESC"
|
||||
rows, err := config.DB.Query(query)
|
||||
// GetPosts 获取所有博客文章(支持搜索)
|
||||
func GetPosts(keyword string) ([]models.Post, error) {
|
||||
var rows *sql.Rows
|
||||
var err error
|
||||
|
||||
if keyword != "" {
|
||||
// 使用全文搜索
|
||||
query := `
|
||||
SELECT id, title, category, date, excerpt, content, read_count, is_published, created_at, updated_at
|
||||
FROM posts
|
||||
WHERE is_published = 1 AND (
|
||||
MATCH(title, content) AGAINST(? IN BOOLEAN MODE) OR
|
||||
title LIKE ? OR
|
||||
content LIKE ?
|
||||
)
|
||||
ORDER BY created_at DESC
|
||||
`
|
||||
likeKeyword := "%" + keyword + "%"
|
||||
rows, err = config.DB.Query(query, keyword, likeKeyword, likeKeyword)
|
||||
} else {
|
||||
// 默认查询
|
||||
query := "SELECT id, title, category, date, excerpt, content, read_count, is_published, created_at, updated_at FROM posts WHERE is_published = 1 ORDER BY created_at DESC"
|
||||
rows, err = config.DB.Query(query)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Printf("Error querying posts: %v", err)
|
||||
return nil, err
|
||||
@@ -43,7 +64,7 @@ func GetPosts() ([]models.Post, error) {
|
||||
}
|
||||
|
||||
// GetPostByID 根据ID获取博客文章
|
||||
func GetPostByID(id string) (*models.Post, error) {
|
||||
func GetPostByID(id uint) (*models.Post, error) {
|
||||
query := "SELECT id, title, category, date, excerpt, content, read_count, is_published, created_at, updated_at FROM posts WHERE id = ? AND is_published = 1"
|
||||
row := config.DB.QueryRow(query, id)
|
||||
|
||||
@@ -78,7 +99,7 @@ func GetPostByID(id string) (*models.Post, error) {
|
||||
|
||||
// GetAllPosts 获取所有博客文章(包括未发布的)
|
||||
func GetAllPosts() ([]models.Post, error) {
|
||||
query := "SELECT id, title, category, date, excerpt, content, read_count, is_published, created_at, updated_at FROM posts ORDER BY date DESC"
|
||||
query := "SELECT id, title, category, date, excerpt, content, read_count, is_published, created_at, updated_at FROM posts ORDER BY created_at DESC"
|
||||
rows, err := config.DB.Query(query)
|
||||
if err != nil {
|
||||
log.Printf("Error querying all posts: %v", err)
|
||||
@@ -113,12 +134,11 @@ func GetAllPosts() ([]models.Post, error) {
|
||||
// CreatePost 创建博客文章
|
||||
func CreatePost(post *models.Post) error {
|
||||
query := `
|
||||
INSERT INTO posts (id, title, category, date, excerpt, content, is_published, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
|
||||
INSERT INTO posts (title, category, date, excerpt, content, is_published, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW())
|
||||
`
|
||||
_, err := config.DB.Exec(
|
||||
result, err := config.DB.Exec(
|
||||
query,
|
||||
post.ID,
|
||||
post.Title,
|
||||
post.Category,
|
||||
post.Date,
|
||||
@@ -131,6 +151,12 @@ func CreatePost(post *models.Post) error {
|
||||
return err
|
||||
}
|
||||
|
||||
id, err := result.LastInsertId()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
post.ID = uint(id)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -159,7 +185,7 @@ func UpdatePost(post *models.Post) error {
|
||||
}
|
||||
|
||||
// DeletePost 删除博客文章
|
||||
func DeletePost(id string) error {
|
||||
func DeletePost(id uint) error {
|
||||
query := "DELETE FROM posts WHERE id = ?"
|
||||
_, err := config.DB.Exec(query, id)
|
||||
if err != nil {
|
||||
@@ -191,7 +217,7 @@ func BuildPostResponse(post *models.Post, includeContent bool) *models.PostRespo
|
||||
ID: post.ID,
|
||||
Title: post.Title,
|
||||
Category: post.Category,
|
||||
Date: post.Date.Format("2006-01-02"),
|
||||
Date: post.Date,
|
||||
Excerpt: post.Excerpt,
|
||||
}
|
||||
|
||||
@@ -225,8 +251,8 @@ func SavePostHistory(post *models.Post, modifiedBy uint) error {
|
||||
insertQuery := `
|
||||
INSERT INTO post_history (
|
||||
post_id, version, title, category, date, excerpt, content,
|
||||
is_published, modified_by, modified_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
|
||||
is_published, modified_by, modified_at, created_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
|
||||
`
|
||||
_, err := config.DB.Exec(
|
||||
insertQuery,
|
||||
@@ -249,7 +275,7 @@ func SavePostHistory(post *models.Post, modifiedBy uint) error {
|
||||
}
|
||||
|
||||
// GetPostHistory 获取文章历史记录
|
||||
func GetPostHistory(postID string) ([]models.PostHistory, error) {
|
||||
func GetPostHistory(postID uint) ([]models.PostHistory, error) {
|
||||
query := `
|
||||
SELECT id, post_id, version, title, category, date, excerpt, content,
|
||||
is_published, modified_by, modified_at, created_at
|
||||
@@ -273,7 +299,7 @@ func GetPostHistory(postID string) ([]models.PostHistory, error) {
|
||||
&h.Version,
|
||||
&h.Title,
|
||||
&h.Category,
|
||||
&h.Date,
|
||||
&h.Date, // Scan date directly into h.Date
|
||||
&h.Excerpt,
|
||||
&h.Content,
|
||||
&h.IsPublished,
|
||||
@@ -291,7 +317,7 @@ func GetPostHistory(postID string) ([]models.PostHistory, error) {
|
||||
}
|
||||
|
||||
// GetPostHistoryByVersion 获取指定版本的文章历史记录
|
||||
func GetPostHistoryByVersion(postID string, version uint) (*models.PostHistory, error) {
|
||||
func GetPostHistoryByVersion(postID uint, version uint) (*models.PostHistory, error) {
|
||||
query := `
|
||||
SELECT id, post_id, version, title, category, date, excerpt, content,
|
||||
is_published, modified_by, modified_at, created_at
|
||||
@@ -333,7 +359,7 @@ func BuildPostHistoryResponse(history *models.PostHistory) *models.PostHistoryRe
|
||||
Version: history.Version,
|
||||
Title: history.Title,
|
||||
Category: history.Category,
|
||||
Date: history.Date.Format("2006-01-02"),
|
||||
Date: history.Date,
|
||||
IsPublished: history.IsPublished,
|
||||
ModifiedBy: history.ModifiedBy,
|
||||
ModifiedAt: history.ModifiedAt.Format("2006-01-02 15:04:05"),
|
||||
|
||||
Reference in New Issue
Block a user