Files
memory/server/internal/router/router.go
2025-12-14 20:33:33 +08:00

89 lines
2.4 KiB
Go

package router
import (
"database/sql"
"memory/internal/config"
"memory/internal/handler"
"memory/internal/middleware"
"github.com/gin-gonic/gin"
)
func Setup(db *sql.DB, cfg *config.Config) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
r.Use(gin.Recovery())
// CORS
r.Use(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
})
// 静态文件服务 (本地上传的文件)
if cfg.LocalUploadPath != "" {
r.Static("/uploads", cfg.LocalUploadPath)
}
// Handlers
authHandler := handler.NewAuthHandler(db, cfg)
postHandler := handler.NewPostHandler(db, cfg)
commentHandler := handler.NewCommentHandler(db, cfg)
userHandler := handler.NewUserHandler(db, cfg)
searchHandler := handler.NewSearchHandler(db, cfg)
uploadHandler := handler.NewUploadHandler(cfg)
// 公开接口
r.POST("/api/auth/register", authHandler.Register)
r.POST("/api/auth/login", authHandler.Login)
// 需要认证的接口
auth := r.Group("/api")
auth.Use(middleware.AuthMiddleware(cfg.JWTSecret))
{
// 帖子
auth.GET("/posts", postHandler.List)
auth.POST("/posts", postHandler.Create)
auth.GET("/posts/:id", postHandler.Get)
auth.DELETE("/posts/:id", postHandler.Delete)
auth.POST("/posts/:id/like", postHandler.Like)
auth.DELETE("/posts/:id/like", postHandler.Unlike)
auth.POST("/posts/:id/reactions", postHandler.AddReaction)
auth.DELETE("/posts/:id/reactions", postHandler.RemoveReaction)
// 评论
auth.GET("/posts/:id/comments", commentHandler.List)
auth.POST("/posts/:id/comments", commentHandler.Create)
auth.DELETE("/posts/:id/comments/:comment_id", commentHandler.Delete)
// 用户
auth.GET("/user/profile", userHandler.GetProfile)
auth.PUT("/user/profile", userHandler.UpdateProfile)
auth.PUT("/user/avatar", userHandler.UpdateAvatar)
// 搜索
auth.GET("/search", searchHandler.Search)
auth.GET("/heatmap", searchHandler.Heatmap)
// 上传
auth.POST("/upload", uploadHandler.Upload)
// 管理员接口
admin := auth.Group("/admin")
admin.Use(middleware.AdminMiddleware())
{
admin.GET("/settings", userHandler.GetSettings)
admin.PUT("/settings", userHandler.UpdateSettings)
}
}
return r
}