Commit 65806016 authored by IronHammer Std's avatar IronHammer Std
Browse files

解耦数据访问

parent a0fbec75
package main
import (
"log"
"os"
"os/signal"
db "BackEnd/db"
)
func main() {
log.Println("INTERN PROJECT - COMMENT SERVICE")
log.Println("Press Ctrl+C to exit")
db.InitDB("./comments.db")
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
go func() {
<-quit
log.Println("Shutting down server...")
db.CloseDB()
os.Exit(0)
}()
initServer()
}
\ No newline at end of file
......@@ -5,7 +5,6 @@ import (
"log"
"net/http"
"strconv"
"sync"
db "BackEnd/db"
)
......@@ -23,12 +22,6 @@ type CommentList struct {
Comments []db.Comment `json:"comments"` // 评论列表
}
var (
mutex sync.RWMutex // 读写锁保护共享数据
comments []db.Comment // 内存存储的评论列表
incrementID int = 1 // 自增ID计数器
)
// 发送统一格式的响应
func sendResponse(w http.ResponseWriter, code int, msg string, data interface{}) {
w.Header().Set("Content-Type", "application/json")
......@@ -79,16 +72,13 @@ func getCommentHandler(w http.ResponseWriter, r *http.Request) {
size = 10
}
mutex.RLock() // 读锁定
defer mutex.RUnlock() // 函数返回时解锁
total := len(comments)
total := db.GetCommentCount()
// 返回所有评论
if size == -1 {
sendResponse(w, 0, "success", CommentList{
Total: total,
Comments: comments,
Comments: db.GetComments(),
})
return
}
......@@ -111,7 +101,7 @@ func getCommentHandler(w http.ResponseWriter, r *http.Request) {
// 返回分页数据
sendResponse(w, 0, "success", CommentList{
Total: total,
Comments: comments[start:end],
Comments: db.GetCommentsSlice(start, end),
})
}
......@@ -152,22 +142,8 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) {
return
}
mutex.Lock() // 写锁定
defer mutex.Unlock() // 函数返回时解锁
// 创建新评论
newComment := db.Comment{
ID: incrementID,
Name: req.Name,
Content: req.Content,
}
incrementID++
// 添加到内存存储
comments = append(comments, newComment)
// 返回新创建的评论
sendResponse(w, 0, "Comment added", newComment)
sendResponse(w, 0, "Comment added", db.AddComment(req.Name, req.Content))
}
// 删除评论处理函数
......@@ -199,19 +175,8 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) {
return
}
mutex.Lock() // 写锁定
defer mutex.Unlock() // 函数返回时解锁
// 查找并删除评论
found := false
for i, comment := range comments {
if comment.ID == id {
// 从切片中删除元素
comments = append(comments[:i], comments[i+1:]...)
found = true
break
}
}
found := db.DeleteComment(id)
if !found {
sendResponse(w, 6, "Comment not found", nil)
......@@ -221,14 +186,8 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) {
sendResponse(w, 0, "Comment deleted", nil)
}
func main() {
// 初始化一些测试数据
comments = []db.Comment{
{ID: 1, Name: "Alice", Content: "First comment!"},
{ID: 2, Name: "Bob", Content: "Great work!"},
}
incrementID = 3
func initServer() {
// 注册路由
http.HandleFunc("/comment/get", getCommentHandler)
http.HandleFunc("/comment/add", addCommentHandler)
......
......@@ -3,7 +3,7 @@ package db
import (
//"fmt"
//"log"
"log"
//"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
......@@ -19,6 +19,19 @@ var (
//once sync.Once
)
func InitDB(dbPath string) {
//TODO
AddComment("Alice", "First comment!")
AddComment("Bob", "Great work!")
log.Println("Database initialized successfully.")
}
func CloseDB() {
//TODO
log.Println("Database closed successfully.")
}
/*
func InitDB(dbPath string) {
......
package db
import (
"sync"
)
var (
mutex = &sync.RWMutex{}
comments []Comment // 内存存储的评论列表
incrementID int = 1 // 自增ID计数器
)
// GetComments 返回当前请求的评论列表
func GetComments() []Comment {
mutex.RLock()
defer mutex.RUnlock()
return comments
}
func GetCommentsSlice(Begin int, End int) []Comment {
mutex.RLock()
defer mutex.RUnlock()
if Begin < 0 || End > len(comments) || Begin > End {
return []Comment{}
}
return comments[Begin:End]
}
func GetCommentCount() int {
mutex.RLock()
defer mutex.RUnlock()
return len(comments)
}
func AddComment(Name string, Content string) Comment {
mutex.Lock()
defer mutex.Unlock()
newComment := Comment{
ID: incrementID,
Name: Name,
Content: Content,
}
incrementID++
comments = append(comments, newComment)
return newComment
}
func DeleteComment(Id int) bool {
mutex.Lock() // 写锁定
defer mutex.Unlock() // 函数返回时解锁
// 查找并删除评论
found := false
for i, comment := range comments {
if comment.ID == Id {
// 从切片中删除元素
comments = append(comments[:i], comments[i+1:]...)
found = true
break
}
}
return found
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment