Commit 45316686 authored by happystarkitty's avatar happystarkitty
Browse files

update

parent 08cdbb17
package db
import (
"database/sql"
//"fmt"
//"log"
//"os"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func InitDB() {
var err error
connStr := "longyue:longyue0511@tcp(127.0.0.1:3306)/Comments"
db, err = sql.Open("mysql", connStr)
if err != nil {
panic(err)
}
err = db.Ping()
if err != nil {
panic(err)
}
}
package db
import (
//"database/sql"
)
//var db *sql.DB
type Comment struct {
ID int `json:"id"`
Name string `json:"name"`
Content string `json:"content"`
}
func GetComment(offset, size int) ([]Comment, error) {
rows, err := db.Query("SELECT id,name,content FROM comments LIMIT ? OFFSET ?", size, offset)
if err != nil {
return nil, err
}
defer rows.Close()
var comments []Comment
for rows.Next() {
var comment Comment
if err := rows.Scan(&comment.ID, &comment.Name, &comment.Content); err != nil {
return nil, err
}
comments = append(comments, comment)
}
if err := rows.Err(); err != nil {
return nil, err
}
return comments, nil
}
func AddComment(name string, content string) (int, error) {
var id int
err := db.QueryRow("INSERT INTO comments (name,content) VALUES(?,?) RETURNING id", name, content).Scan(&id)
if err != nil {
return 0, err
}
return id, nil
}
func DeleteComment(commentID int) error {
_, err := db.Exec("DELETE FROM comments WHERE id = ?", commentID)
return err
}
func GetTotalComments() (int, error) {
var total int
err := db.QueryRow("SELECT COUNT(*) FROM comments").Scan(&total)
if err != nil {
return 0, err
}
return total, err
}
module BackEnd
go 1.22.3
require (
github.com/go-sql-driver/mysql v1.8.1
github.com/rs/cors v1.11.0
)
require filippo.io/edwards25519 v1.1.0 // indirect
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po=
github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
package main
import (
"BackEnd/db"
"BackEnd/server"
"github.com/rs/cors"
"log"
"net/http"
)
func main() {
db.InitDB()
mux := http.NewServeMux()
mux.HandleFunc("/comment/get", server.GetComment)
mux.HandleFunc("/comment/add", server.AddComment)
mux.HandleFunc("/comment/delete", server.DeleteComment)
handler := cors.Default().Handler(mux)
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", handler); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}
package server
import (
"BackEnd/db"
"encoding/json"
//"github.com/rs/cors"
"net/http"
"strconv"
//"sync"
)
type GetData struct {
Total int `json:"total"`
Comments []db.Comment `json:"comments"`
}
type AddCommentRequest struct {
Name string `json:"name"`
Content string `json:"content"`
}
type GetCommentResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data GetData `json:"data"`
}
type AddCommentResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data db.Comment `json:"data"`
}
type DeleteCommentResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data db.Comment `json:"data"`
}
func GetComment(w http.ResponseWriter, r *http.Request) {
pageStr := r.URL.Query().Get("page")
sizeStr := r.URL.Query().Get("size")
page, err := strconv.Atoi(pageStr)
if err != nil || page < 1 {
page = 1
}
size, err := strconv.Atoi(sizeStr)
if err != nil || size < 1 {
size = 10
}
dbComments, err := db.GetComment(page, size)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
start := (page - 1) * size
end := start + size
if start > len(dbComments) {
start = len(dbComments)
}
if end > len(dbComments) {
end = len(dbComments)
}
pagedComments := dbComments[start:end]
comments := make([]db.Comment, len(pagedComments))
for i, c := range pagedComments {
comments[i] = db.Comment{
ID: c.ID,
Name: c.Name,
Content: c.Content,
}
}
var response GetCommentResponse
response.Code = 0
response.Msg = "success"
response.Data.Total = len(dbComments)
response.Data.Comments = comments
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(response)
}
func AddComment(w http.ResponseWriter, r *http.Request) {
var req AddCommentRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
id, err := db.AddComment(req.Name, req.Content)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
newComment := db.Comment{
ID: id,
Name: req.Name,
Content: req.Content,
}
var response AddCommentResponse
response.Data = newComment
response.Code = 0
response.Msg = "success"
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(response)
}
func DeleteComment(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
http.Error(w, "Missing id", http.StatusBadRequest)
return
}
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid id", http.StatusBadRequest)
return
}
if err := db.DeleteComment(id); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var response DeleteCommentResponse
response.Code = 0
response.Msg = "success"
w.Header().Set("Content-Type", "application/json;charset=utf-8")
json.NewEncoder(w).Encode(response)
}
......@@ -2,7 +2,8 @@
<html lang="en-US">
<head>
<meta charset="utf-8">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>评论区</title>
<link rel="stylesheet" href="style.css">
</head>
......@@ -22,40 +23,16 @@
</div>
<br>
<div class="comment_box" id="comment1">
<h3>name</h3>
<div>
<p>第一条评论</p>
<div id="commentSection">
</div>
<button class="delete_button">
删除
</button>
</div>
</div>
<br>
<div class="comment_box">
<h3>name</h3>
<p>第二条评论</p>
<button class="delete_button">
删除
<div>
<button id="previousPage">前页</button>
<button id="nextPage">后页
</button>
</div>
<br>
<div class="comment_box">
<h3>name</h3>
<div>
<p>第三条评论</p>
<button class="delete_button">
删除
</button>
</div>
</div>
<script src="jquery.js"></script>
<script src="script.js"></script>
</body>
......
const html = document.querySelector("html");
const html=document.querySelector("html");
const commentSection = document.querySelector("#commentSection");
const submitButton = document.querySelector("#submitButton");
const userNameInput = document.querySelector("#userName");
const commentContentInput = document.querySelector("#commentContent");
const deleteButton = document.querySelectorAll(".deleteButton");
const previousPageButton=document.querySelector("#previousPage")
const nextPageButton=document.querySelector("#nextPage")
let currentPage=1;
const pageSize=10;
let commentNumber = 0;
function resetInput() {
userNameInput.value = "";
commentContentInput.value = "";
}
function createComment() {
function deleteComment(event){
const comment = event.target.parentElement;
const commentId=comment.getAttribute("data-id");
html.removeChild(comment);
fetch(`http://localhost:8080/comment/delete?id=${commentId}`,{
method:'DELETE',
headers:{
'Content-Type':'application/json'
}
})
.then(response=>response.json())
.then(data=>{
if (data.code===0){
console.log("Comment deleted successfully");
}else{
console.error("Failed to delete comment",data.msg);
}
}
)
.catch(error=>{
console.error("Error:",error);
});}
function addComment() {
const userName = userNameInput.value;
const commentContent = commentContentInput.value;
commentNumber = commentNumber + 1;
let comment = document.createElement("div");
comment.className = "comment_box";
fetch('http://localhost:8080/comment/add',{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
name:userName,
content:commentContent
})
})
.then(response =>response.json())
.then(data=>{
if(data.code===0){
console.log("Comment added succesfully");
getComment(currentPage,pageSize);
}else{
console.error("Error adding comment:",data.msg);
}
})
.catch(error=>console.error("Error:",error));
resetInput();}
submitButton.addEventListener("click", addComment);
function getComment(page,size){
fetch(`http://localhost:8080/comment/get?page=${page}&size=${size}`,{
method:'GET'}
)
.then(response=>response.json())
.then(data=>{
if (data.code===0){
console.log("Comments fetched successfully");
renderComments(data.data);
updatePaginationButtons(data.total);
}else{
console.error("Error fetching comments:",data.msg);
}
})
.catch(error=>console.error("Error:",error));
}
let commentatorName = document.createElement("h3");
let commentatorNameText = document.createTextNode(userName);
commentatorName.appendChild(commentatorNameText);
function renderComments(comments){
commentSection.innerHTML="";
if(Array.isArray(comments)){
comments.forEach(comment =>{
const commentDiv=document.createElement("div");
commentDiv.className="comment_box";
const commentatorName=document.createElement("h3");
commentatorName.textContent=comment.name;
const commentatorContent=document.createElement("p");
commentatorContent.textContent=comment.content;
const deleteButton=document.createElement("button");
deleteButton.textContent="删除";
deleteButton.addEventListener("click",deleteComment);
let commentatorComment = document.createElement("p");
let commentatorCommentText = document.createTextNode(commentContent);
commentatorComment.appendChild(commentatorCommentText);
commentDiv.appendChild(commentatorName);
commentDiv.appendChild(commentatorContent);
commentDiv.appendChild(deleteButton);
commentSection.appendChild(commentDiv);
});}
else {
console.error("Comments data is not an array");
}
}
function deleteComment(commentID){
fetch('http://localhost:8080/comment/delete?id=${commentID}',{
method:'DELETE'
})
.then(response=>response.json())
.then(data=>{
if(data.code===0){
console.log("Comment deleted successfully");
getComment(currentPage,pageSize);
}else{
console.error("Error deleting comment:",data.msg);
}
})
.catch(error=>console.error("Error:".error));
}
let deleteButton = document.createElement("button");
deleteButton.className = "operation_button";
let deleteButtonText = document.createTextNode("删除");
deleteButton.appendChild(deleteButtonText);
deleteButton.addEventListener("click", () => { html.removeChild(comment) });
comment.appendChild(commentatorName);
comment.appendChild(commentatorComment);
comment.appendChild(deleteButton);
html.appendChild(comment);
resetInput();
function updatePaginationButtons(totalComments){
const totalPages=Math.ceil(totalComments/pageSize);
previousPageButton.disabled=currentPage<=1;
nextPageButton.disabled=currentPage>=totalPages;
}
function handlePreviousPage(){
if (currentPage >1){
currentPage--;
getComment(currentPage,pageSize);
}
}
function handleNextPage(){
currentPage++;
getComment(currentPage,pageSize);
}
submitButton.addEventListener("click", createComment);
previousPageButton.addEventListener("click",handlePreviousPage)
nextPageButton.addEventListener("click",handleNextPage);
getComment(currentPage,pageSize);
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