router.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package router
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "note-manager/config"
  5. "note-manager/handler"
  6. "note-manager/middleware"
  7. )
  8. // Setup 初始化路由
  9. func Setup(r *gin.Engine, noteHandler *handler.NoteHandler, adminHandler *handler.AdminHandler, imageHandler *handler.ImageHandler, cfg *config.Config) *gin.Engine {
  10. // 全局中间件
  11. r.Use(middleware.CORS())
  12. // 静态文件服务(图片)
  13. r.Static("/uploads", cfg.UploadDir)
  14. // API 路由组
  15. api := r.Group("/api")
  16. {
  17. notes := api.Group("/notes")
  18. {
  19. // 公开只读接口
  20. notes.GET("", noteHandler.ListNotes)
  21. notes.GET("/search", noteHandler.SearchNotes)
  22. notes.GET("/:id", noteHandler.GetNote)
  23. notes.POST("/:id/access", noteHandler.AccessNote) // 密码验证访问
  24. // 需要认证的管理接口
  25. notes.POST("", noteHandler.CreateNote)
  26. notes.PUT("/:id", noteHandler.UpdateNote)
  27. notes.DELETE("/:id", noteHandler.DeleteNote)
  28. }
  29. api.GET("/categories", noteHandler.GetCategories)
  30. api.GET("/tags", noteHandler.GetTags)
  31. api.GET("/tree", noteHandler.GetPublicTree) // 前台公开树
  32. }
  33. // 管理后台专用 API(需要认证)
  34. adminApi := r.Group("/admin/api")
  35. adminApi.Use(func(c *gin.Context) {
  36. token, err := c.Cookie("admin_token")
  37. if err != nil || token != "authenticated" {
  38. c.JSON(401, gin.H{"code": 401, "message": "请先登录"})
  39. c.Abort()
  40. return
  41. }
  42. c.Next()
  43. })
  44. {
  45. adminApi.GET("/tree", noteHandler.GetTree) // 后台完整树
  46. adminApi.POST("/upload", imageHandler.Upload) // 图片上传
  47. adminApi.GET("/export/:id", noteHandler.ExportNote) // 导出笔记
  48. adminApi.POST("/import", noteHandler.ImportNotes) // 导入笔记
  49. }
  50. // 后台管理路由
  51. admin := r.Group("/admin")
  52. {
  53. admin.GET("/login", adminHandler.LoginPage)
  54. admin.POST("/login", adminHandler.Login)
  55. admin.POST("/logout", adminHandler.Logout)
  56. admin.GET("/auth", adminHandler.CheckAuth)
  57. admin.GET("/", adminHandler.IndexPage)
  58. }
  59. // 健康检查
  60. r.GET("/health", func(c *gin.Context) {
  61. c.JSON(200, gin.H{"status": "ok"})
  62. })
  63. // 前端页面 - 根路径返回展示页面
  64. r.GET("/", func(c *gin.Context) {
  65. c.File("./web/index.html")
  66. })
  67. return r
  68. }