Commit 80ac27b3 authored by Zhu yizheng's avatar Zhu yizheng
Browse files

完成跨域

parent e5a34ae1
...@@ -6,24 +6,28 @@ import ( ...@@ -6,24 +6,28 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
) )
// DB 全局数据库实例 // DB 全局数据库实例(保持不变)
var DB *gorm.DB var DB *gorm.DB
// InitDB 初始化 PostgreSQL 数据库 // InitDB 初始化 PostgreSQL 数据库(修改:返回error类型)
func InitDB() { func InitDB() error { // 关键:添加error返回值
// PostgreSQL 连接字符串 // PostgreSQL 连接字符串(替换为你的实际配置)
// 替换为你的实际配置:host、port、user、password、dbname dsn := "host=localhost port=5432 user=go_zyz password=zyz757605 dbname=mygo sslmode=disable client_encoding=utf8"
dsn := "host=localhost port=5432 user=go_zyz password=zyz757605 dbname=mygo sslmode=disable"
var err error var err error
// 连接数据库
DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{}) DB, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil { if err != nil {
logrus.WithError(err).Fatal("数据库连接失败") logrus.WithError(err).Error("数据库连接失败") // 改为Error(不退出)
return err // 返回错误
} }
// 自动迁移创建/更新 Comment // 自动迁移表(创建/更新Comment表
if err := DB.AutoMigrate(&Comment{}); err != nil { if err := DB.AutoMigrate(&Comment{}); err != nil {
logrus.WithError(err).Fatal("数据库迁移失败") logrus.WithError(err).Error("数据库迁移失败") // 改为Error(不退出)
return err // 返回错误
} }
logrus.Info("PostgreSQL 数据库初始化成功") logrus.Info("PostgreSQL 数据库初始化成功")
return nil // 成功返回nil
} }
...@@ -3,28 +3,65 @@ package main ...@@ -3,28 +3,65 @@ package main
import ( import (
"net/http" "net/http"
"github.com/zyz/comment-api/db"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/zyz/comment-api/db" // 保留数据库包导入(正确)
) )
// ------------------------------
// CORS中间件(保持不变,解决跨域问题)
// ------------------------------
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 允许的前端Origin(修改为你的前端实际地址,如http://localhost:5500)
allowedOrigins := []string{
"http://localhost:5500", // 保留原有的localhost
"http://127.0.0.1:5500", // 添加前端实际的Origin(Live Server的地址)
}
origin := r.Header.Get("Origin")
for _, o := range allowedOrigins {
if o == origin {
w.Header().Set("Access-Control-Allow-Origin", origin)
break
}
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func main() { func main() {
// 初始化日志 // 初始化日志(保持不变)
logrus.SetFormatter(&logrus.JSONFormatter{}) logrus.SetFormatter(&logrus.JSONFormatter{})
logrus.Info("启动服务器...") logrus.Info("启动服务器...")
// 初始化数据库 // 初始化数据库(修改:接收error并处理)
db.InitDB() if err := db.InitDB(); err != nil { // 现在db.InitDB()返回error,可正确接收
logrus.WithError(err).Fatal("数据库初始化失败") // 这里用Fatal退出程序
}
logrus.Info("PostgreSQL 数据库初始化成功")
// 注册路由(直接使用main包中的函数,无需前缀)
mux := http.NewServeMux()
mux.HandleFunc("/comment/get", GetCommentsHandler) // 直接使用GetCommentsHandler(来自server.go)
mux.HandleFunc("/comment/add", AddCommentHandler) // 直接使用AddCommentHandler(来自server.go)
mux.HandleFunc("/comment/delete", DeleteCommentHandler) // 直接使用DeleteCommentHandler(来自server.go)
// 注册路由 // 应用CORS中间件(保持不变)
http.HandleFunc("/comment/get", getCommentsHandler) handler := corsMiddleware(mux)
http.HandleFunc("/comment/add", addCommentHandler)
http.HandleFunc("/comment/delete", deleteCommentHandler)
// 启动服务器 // 启动服务器(保持不变)
addr := ":8080" addr := ":8080"
logrus.WithField("address", addr).Info("服务器启动") logrus.WithField("address", addr).Info("服务器启动")
if err := http.ListenAndServe(addr, nil); err != nil { if err := http.ListenAndServe(addr, handler); err != nil {
logrus.WithError(err).Fatal("服务器启动失败") logrus.WithError(err).Fatal("服务器启动失败")
} }
} }
package main package main // 必须是main包,和main.go同目录
import ( import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"strconv" "strconv"
"github.com/zyz/comment-api/db"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
"github.com/zyz/comment-api/db"
"gorm.io/gorm" "gorm.io/gorm"
) )
// Response 统一响应格式 // Response 统一响应格式(保持不变)
type Response struct { type Response struct {
Code int `json:"code"` Code int `json:"code"`
Msg string `json:"msg"` Msg string `json:"msg"`
Data interface{} `json:"data"` Data interface{} `json:"data"`
} }
// GetCommentsResponse 获取评论响应 // GetCommentsResponse 获取评论响应(保持不变)
type GetCommentsResponse struct { type GetCommentsResponse struct {
Total int64 `json:"total"` Total int64 `json:"total"`
Comments []db.Comment `json:"comments"` Comments []db.Comment `json:"comments"`
} }
func getCommentsHandler(w http.ResponseWriter, r *http.Request) { // ------------------------------
// 导出函数(首字母大写,main包中可直接使用)
// ------------------------------
func GetCommentsHandler(w http.ResponseWriter, r *http.Request) { // 首字母大写,导出
log := logrus.WithFields(logrus.Fields{ log := logrus.WithFields(logrus.Fields{
"method": r.Method, "method": r.Method,
"path": r.URL.Path, "path": r.URL.Path,
...@@ -35,21 +37,18 @@ func getCommentsHandler(w http.ResponseWriter, r *http.Request) { ...@@ -35,21 +37,18 @@ func getCommentsHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 解析分页参数
page, size := parsePaginationParams(r) page, size := parsePaginationParams(r)
log = log.WithFields(logrus.Fields{ log = log.WithFields(logrus.Fields{
"page": page, "page": page,
"size": size, "size": size,
}) })
// 查询数据库
comments, total, err := db.GetComments(page, size) comments, total, err := db.GetComments(page, size)
if err != nil { if err != nil {
respondError(w, http.StatusInternalServerError, "查询评论失败", nil, log.WithError(err)) respondError(w, http.StatusInternalServerError, "查询评论失败", nil, log.WithError(err))
return return
} }
// 准备响应
data := GetCommentsResponse{ data := GetCommentsResponse{
Total: total, Total: total,
Comments: comments, Comments: comments,
...@@ -57,7 +56,7 @@ func getCommentsHandler(w http.ResponseWriter, r *http.Request) { ...@@ -57,7 +56,7 @@ func getCommentsHandler(w http.ResponseWriter, r *http.Request) {
respondSuccess(w, data, log) respondSuccess(w, data, log)
} }
func addCommentHandler(w http.ResponseWriter, r *http.Request) { func AddCommentHandler(w http.ResponseWriter, r *http.Request) { // 首字母大写,导出
log := logrus.WithFields(logrus.Fields{ log := logrus.WithFields(logrus.Fields{
"method": r.Method, "method": r.Method,
"path": r.URL.Path, "path": r.URL.Path,
...@@ -68,7 +67,6 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) { ...@@ -68,7 +67,6 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 解析请求体
var req struct { var req struct {
Name string `json:"name"` Name string `json:"name"`
Content string `json:"content"` Content string `json:"content"`
...@@ -78,13 +76,11 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) { ...@@ -78,13 +76,11 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 验证输入
if req.Name == "" || req.Content == "" { if req.Name == "" || req.Content == "" {
respondError(w, http.StatusBadRequest, "姓名和内容为必填项", nil, log) respondError(w, http.StatusBadRequest, "姓名和内容为必填项", nil, log)
return return
} }
// 创建评论
comment, err := db.CreateComment(req.Name, req.Content) comment, err := db.CreateComment(req.Name, req.Content)
if err != nil { if err != nil {
respondError(w, http.StatusInternalServerError, "创建评论失败", nil, log.WithError(err)) respondError(w, http.StatusInternalServerError, "创建评论失败", nil, log.WithError(err))
...@@ -94,7 +90,7 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) { ...@@ -94,7 +90,7 @@ func addCommentHandler(w http.ResponseWriter, r *http.Request) {
respondSuccess(w, comment, log) respondSuccess(w, comment, log)
} }
func deleteCommentHandler(w http.ResponseWriter, r *http.Request) { func DeleteCommentHandler(w http.ResponseWriter, r *http.Request) { // 首字母大写,导出
log := logrus.WithFields(logrus.Fields{ log := logrus.WithFields(logrus.Fields{
"method": r.Method, "method": r.Method,
"path": r.URL.Path, "path": r.URL.Path,
...@@ -105,7 +101,6 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) { ...@@ -105,7 +101,6 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 解析评论 ID
idStr := r.URL.Query().Get("id") idStr := r.URL.Query().Get("id")
id, err := strconv.Atoi(idStr) id, err := strconv.Atoi(idStr)
if err != nil || id <= 0 { if err != nil || id <= 0 {
...@@ -113,7 +108,6 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) { ...@@ -113,7 +108,6 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) {
return return
} }
// 删除评论
if err := db.DeleteComment(id); err != nil { if err := db.DeleteComment(id); err != nil {
if err == gorm.ErrRecordNotFound { if err == gorm.ErrRecordNotFound {
respondError(w, http.StatusNotFound, "评论不存在", nil, log) respondError(w, http.StatusNotFound, "评论不存在", nil, log)
...@@ -126,7 +120,7 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) { ...@@ -126,7 +120,7 @@ func deleteCommentHandler(w http.ResponseWriter, r *http.Request) {
respondSuccess(w, nil, log) respondSuccess(w, nil, log)
} }
// parsePaginationParams 解析分页参数 // parsePaginationParams 解析分页参数(保持不变)
func parsePaginationParams(r *http.Request) (page, size int) { func parsePaginationParams(r *http.Request) (page, size int) {
pageStr := r.URL.Query().Get("page") pageStr := r.URL.Query().Get("page")
sizeStr := r.URL.Query().Get("size") sizeStr := r.URL.Query().Get("size")
...@@ -144,7 +138,7 @@ func parsePaginationParams(r *http.Request) (page, size int) { ...@@ -144,7 +138,7 @@ func parsePaginationParams(r *http.Request) (page, size int) {
return page, size return page, size
} }
// respondSuccess 发送成功响应 // respondSuccess 发送成功响应(保持不变)
func respondSuccess(w http.ResponseWriter, data interface{}, log *logrus.Entry) { func respondSuccess(w http.ResponseWriter, data interface{}, log *logrus.Entry) {
resp := Response{ resp := Response{
Code: 0, Code: 0,
...@@ -154,7 +148,7 @@ func respondSuccess(w http.ResponseWriter, data interface{}, log *logrus.Entry) ...@@ -154,7 +148,7 @@ func respondSuccess(w http.ResponseWriter, data interface{}, log *logrus.Entry)
sendResponse(w, http.StatusOK, resp, log) sendResponse(w, http.StatusOK, resp, log)
} }
// respondError 发送错误响应 // respondError 发送错误响应(保持不变)
func respondError(w http.ResponseWriter, status int, msg string, data interface{}, log *logrus.Entry) { func respondError(w http.ResponseWriter, status int, msg string, data interface{}, log *logrus.Entry) {
resp := Response{ resp := Response{
Code: status, Code: status,
...@@ -168,9 +162,10 @@ func respondError(w http.ResponseWriter, status int, msg string, data interface{ ...@@ -168,9 +162,10 @@ func respondError(w http.ResponseWriter, status int, msg string, data interface{
sendResponse(w, status, resp, log) sendResponse(w, status, resp, log)
} }
// sendResponse 发送 JSON 响应 // sendResponse 发送JSON响应(保持不变)
func sendResponse(w http.ResponseWriter, status int, resp Response, log *logrus.Entry) { func sendResponse(w http.ResponseWriter, status int, resp Response, log *logrus.Entry) {
w.Header().Set("Content-Type", "application/json") // 关键:添加charset=utf-8
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status) w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(resp); err != nil { if err := json.NewEncoder(w).Encode(resp); err != nil {
log.WithError(err).Error("发送响应失败") log.WithError(err).Error("发送响应失败")
......
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