75 lines
2.8 KiB
Go
75 lines
2.8 KiB
Go
// Package router 配置API路由和中间件
|
||
// 定义所有HTTP接口路径、处理函数和CORS等中间件
|
||
package router
|
||
|
||
import (
|
||
"excel-api/handlers"
|
||
ws "excel-api/websocket"
|
||
|
||
"github.com/gin-gonic/gin"
|
||
)
|
||
|
||
// Setup 初始化并返回配置好的Gin引擎
|
||
// 包含所有API路由、中间件配置
|
||
// hub: WebSocket连接管理中心实例
|
||
func Setup(hub *ws.Hub) *gin.Engine {
|
||
r := gin.Default()
|
||
|
||
// 配置CORS中间件,允许前端跨域请求
|
||
r.Use(CORSMiddleware())
|
||
|
||
// 静态文件服务:上传的文件通过 /uploads/ 路径访问
|
||
r.Static("/uploads", "./uploads")
|
||
|
||
// API路由组
|
||
api := r.Group("/api")
|
||
{
|
||
// ========== 工作簿相关接口 ==========
|
||
api.GET("/workbooks", handlers.GetWorkbooks) // 获取工作簿列表
|
||
api.POST("/workbooks", handlers.CreateWorkbook) // 创建新工作簿
|
||
api.GET("/workbooks/:id", handlers.GetWorkbook) // 获取工作簿详情
|
||
api.PUT("/workbooks/:id", handlers.UpdateWorkbook) // 更新工作簿
|
||
api.DELETE("/workbooks/:id", handlers.DeleteWorkbook) // 删除工作簿
|
||
|
||
// ========== 工作表相关接口 ==========
|
||
api.GET("/workbooks/:wid/sheets", handlers.GetSheets) // 获取工作簿下的工作表列表
|
||
api.POST("/workbooks/:wid/sheets", handlers.CreateSheet) // 在工作簿下创建新工作表
|
||
api.GET("/sheets/:id", handlers.GetSheet) // 获取工作表详情
|
||
api.PUT("/sheets/:id", handlers.UpdateSheet) // 更新工作表
|
||
api.DELETE("/sheets/:id", handlers.DeleteSheet) // 删除工作表
|
||
|
||
// ========== 单元格相关接口 ==========
|
||
api.GET("/sheets/:id/cells", handlers.GetCells) // 获取单元格数据(支持范围查询)
|
||
api.POST("/sheets/:id/cells", handlers.BatchUpdateCells) // 批量更新单元格
|
||
|
||
// ========== 文件上传接口 ==========
|
||
api.POST("/upload", handlers.Upload) // 上传文件
|
||
|
||
// ========== WebSocket接口 ==========
|
||
api.GET("/ws", ws.HandleWebSocket(hub)) // WebSocket连接端点
|
||
|
||
// ========== 预检请求处理 ==========
|
||
api.OPTIONS("/*path", handlers.HandleOptions) // 处理CORS预检请求
|
||
}
|
||
|
||
return r
|
||
}
|
||
|
||
// CORSMiddleware 返回CORS跨域中间件
|
||
// 允许前端开发服务器(端口8888)跨域访问后端API
|
||
func CORSMiddleware() gin.HandlerFunc {
|
||
return func(c *gin.Context) {
|
||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
|
||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE, PATCH")
|
||
|
||
if c.Request.Method == "OPTIONS" {
|
||
c.AbortWithStatus(204)
|
||
return
|
||
}
|
||
|
||
c.Next()
|
||
}
|
||
}
|