107 lines
2.6 KiB
Go
107 lines
2.6 KiB
Go
package handlers
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/niangaodev/art-code/models"
|
|
"github.com/niangaodev/art-code/repositories"
|
|
)
|
|
|
|
// 获取代码片段列表
|
|
func GetSnippets(c *gin.Context) {
|
|
// 从数据库获取所有代码片段
|
|
snippets, err := repositories.GetSnippets()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch snippets"})
|
|
return
|
|
}
|
|
|
|
// 构建响应
|
|
responses := repositories.BuildSnippetsResponse(snippets)
|
|
|
|
c.JSON(http.StatusOK, responses)
|
|
}
|
|
|
|
func GetSnippet(c *gin.Context) {
|
|
id := c.Param("id")
|
|
// 从数据库获取代码片段
|
|
snippet, err := repositories.GetSnippetByID(id)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch snippet"})
|
|
return
|
|
}
|
|
|
|
if snippet == nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "Snippet not found"})
|
|
return
|
|
}
|
|
|
|
// 构建响应
|
|
response := repositories.BuildSnippetResponse(snippet)
|
|
|
|
c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// 获取代码片段列表 (Admin)
|
|
func AdminGetSnippets(c *gin.Context) {
|
|
snippets, err := repositories.GetSnippets()
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get snippets"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, repositories.BuildSnippetsResponse(snippets))
|
|
}
|
|
|
|
// 创建代码片段
|
|
func AdminCreateSnippet(c *gin.Context) {
|
|
var snippet models.Snippet
|
|
if err := c.ShouldBindJSON(&snippet); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
|
return
|
|
}
|
|
|
|
// 创建代码片段
|
|
if err := repositories.CreateSnippet(&snippet); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create snippet"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "Snippet created successfully"})
|
|
}
|
|
|
|
// 更新代码片段
|
|
func AdminUpdateSnippet(c *gin.Context) {
|
|
snippetID := c.Param("id")
|
|
var snippet models.Snippet
|
|
if err := c.ShouldBindJSON(&snippet); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
|
|
return
|
|
}
|
|
|
|
// 设置代码片段ID
|
|
snippet.ID = snippetID
|
|
|
|
// 更新代码片段
|
|
if err := repositories.UpdateSnippet(&snippet); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update snippet"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "Snippet updated successfully"})
|
|
}
|
|
|
|
// 删除代码片段
|
|
func AdminDeleteSnippet(c *gin.Context) {
|
|
snippetID := c.Param("id")
|
|
|
|
// 删除代码片段
|
|
if err := repositories.DeleteSnippet(snippetID); err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete snippet"})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{"message": "Snippet deleted successfully"})
|
|
}
|