Files
HouseholdBudgetBook/backend/api/router.go
T

263 lines
7.6 KiB
Go

package api
import (
"database/sql"
"io"
"mime"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"household-book/middleware"
"household-book/service"
"github.com/gin-gonic/gin"
)
func SetupRouter(db *sql.DB, dbPath string, mode string, staticDir string, corsOrigins string) *gin.Engine {
if mode == "prod" {
gin.SetMode(gin.ReleaseMode)
} else {
gin.SetMode(gin.DebugMode)
}
r := gin.New()
middleware.Setup(r, mode, corsOrigins)
memberSvc := service.NewMemberService(db)
categorySvc := service.NewCategoryService(db)
accountSvc := service.NewAccountService(db)
transactionSvc := service.NewTransactionService(db)
dashboardSvc := service.NewDashboardService(db)
budgetSvc := service.NewBudgetService(db)
reportSvc := service.NewReportService(db)
assetSvc := service.NewAssetService(db)
policySvc := service.NewPolicyService(db)
lifecycleSvc := service.NewLifecycleService(db)
backupSvc := service.NewBackupService(db, dbPath)
memberH := NewMemberHandler(memberSvc)
categoryH := NewCategoryHandler(categorySvc)
accountH := NewAccountHandler(accountSvc)
transactionH := NewTransactionHandler(transactionSvc)
dashboardH := NewDashboardHandler(dashboardSvc)
budgetH := NewBudgetHandler(budgetSvc)
reportH := NewReportHandler(reportSvc)
assetH := NewAssetHandler(assetSvc)
policyH := NewPolicyHandler(policySvc)
lifecycleH := NewLifecycleHandler(lifecycleSvc)
backupH := NewBackupHandler(backupSvc)
api := r.Group("/api")
{
api.GET("/members", memberH.List)
api.POST("/members", memberH.Create)
api.PUT("/members/:id", memberH.Update)
api.DELETE("/members/:id", memberH.Delete)
api.GET("/categories", categoryH.List)
api.POST("/categories", categoryH.Create)
api.PUT("/categories/:id", categoryH.Update)
api.DELETE("/categories/:id", categoryH.Delete)
api.GET("/accounts", accountH.List)
api.POST("/accounts", accountH.Create)
api.PUT("/accounts/:id", accountH.Update)
api.DELETE("/accounts/:id", accountH.Delete)
api.POST("/accounts/:id/reconcile", accountH.Reconcile)
api.GET("/accounts/:id/reconciliations", accountH.ListReconciliations)
api.GET("/transactions", transactionH.List)
api.GET("/transactions/import-batches", transactionH.ListImportBatches)
api.POST("/transactions/import/preview", transactionH.PreviewImport)
api.POST("/transactions/import", transactionH.Import)
api.POST("/transactions/batch-delete", transactionH.DeleteBatch)
api.POST("/transactions", transactionH.Create)
api.PUT("/transactions/:id", transactionH.Update)
api.DELETE("/transactions/:id", transactionH.Delete)
api.DELETE("/transactions/import-batches/:id", transactionH.DeleteImportBatch)
api.GET("/dashboard/summary", dashboardH.Summary)
api.GET("/dashboard/recent", dashboardH.Recent)
api.GET("/budgets/:year/:month", budgetH.Overview)
api.PUT("/budgets", budgetH.Upsert)
api.DELETE("/budgets/:id", budgetH.Delete)
api.GET("/reports/overview", reportH.Overview)
api.GET("/reports/category-ranking", reportH.CategoryRanking)
api.GET("/reports/trend", reportH.Trend)
api.GET("/assets", assetH.ListAssets)
api.POST("/assets", assetH.CreateAsset)
api.PUT("/assets/:id", assetH.UpdateAsset)
api.DELETE("/assets/:id", assetH.DeleteAsset)
api.GET("/assets/net-worth", assetH.NetWorth)
api.GET("/assets/snapshots", assetH.ListSnapshots)
api.GET("/liabilities", assetH.ListLiabilities)
api.POST("/liabilities", assetH.CreateLiability)
api.PUT("/liabilities/:id", assetH.UpdateLiability)
api.DELETE("/liabilities/:id", assetH.DeleteLiability)
api.GET("/policies", policyH.List)
api.POST("/policies", policyH.Create)
api.PUT("/policies/:id", policyH.Update)
api.DELETE("/policies/:id", policyH.Delete)
api.GET("/policies/upcoming", policyH.Upcoming)
api.GET("/policies/:id/payments", policyH.ListPayments)
api.POST("/policies/:id/payments", policyH.CreatePayment)
api.PUT("/policy-payments/:id", policyH.UpdatePayment)
api.GET("/lifecycle", lifecycleH.List)
api.POST("/lifecycle/events", lifecycleH.Create)
api.PUT("/lifecycle/events/:id", lifecycleH.Update)
api.DELETE("/lifecycle/events/:id", lifecycleH.Delete)
api.GET("/backups/status", backupH.Status)
api.POST("/backups", backupH.Create)
}
// Production: serve static files
if staticDir != "" {
r.Use(staticFileMiddleware(staticDir))
}
return r
}
// immutableAssetPrefix 是 Vite 构建产物目录,文件名自带内容 hash,可长期强缓存。
const immutableAssetPrefix = "/assets/"
func staticFileMiddleware(staticDir string) gin.HandlerFunc {
fs := http.FileServer(http.Dir(staticDir))
root, err := filepath.Abs(staticDir)
if err != nil {
root = staticDir
}
indexPath := filepath.Join(root, "index.html")
return func(c *gin.Context) {
requestPath := c.Request.URL.Path
if strings.HasPrefix(requestPath, "/api") {
c.Next()
return
}
// 根路径与入口页直接返回 index.html,省掉文件服务器的目录重定向;
// 入口页必须每次协商,否则前端发版后用户会继续使用旧 bundle。
if requestPath == "/" || requestPath == "/index.html" {
if serveIndexHTML(c, indexPath) {
c.Abort()
return
}
c.Next()
return
}
clean := filepath.Clean("/" + requestPath)
candidate := filepath.Join(root, clean)
if !strings.HasPrefix(candidate, root) {
c.Next()
return
}
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
setStaticCacheHeaders(c, requestPath)
if servePrecompressed(c, candidate) {
c.Abort()
return
}
fs.ServeHTTP(c.Writer, c.Request)
c.Abort()
return
}
// SPA fallback
if serveIndexHTML(c, indexPath) {
c.Abort()
return
}
c.Next()
}
}
// serveIndexHTML 返回入口页;文件不存在时返回 false,交回路由继续处理。
func serveIndexHTML(c *gin.Context, indexPath string) bool {
if _, err := os.Stat(indexPath); err != nil {
return false
}
c.Header("Cache-Control", "no-cache, must-revalidate")
c.File(indexPath)
return true
}
func setStaticCacheHeaders(c *gin.Context, requestPath string) {
if strings.HasPrefix(requestPath, immutableAssetPrefix) {
c.Header("Cache-Control", "public, max-age=31536000, immutable")
return
}
c.Header("Cache-Control", "public, max-age=3600")
}
// servePrecompressed 在存在 .br/.gz 预压缩副本时直接返回;返回 true 表示已写入响应。
func servePrecompressed(c *gin.Context, filePath string) bool {
encoding := preferredEncoding(c.GetHeader("Accept-Encoding"))
if encoding == "" {
return false
}
compressedPath := filePath + "." + compressedSuffix(encoding)
info, err := os.Stat(compressedPath)
if err != nil || info.IsDir() {
return false
}
file, err := os.Open(compressedPath)
if err != nil {
return false
}
defer file.Close()
if contentType := mime.TypeByExtension(filepath.Ext(filePath)); contentType != "" {
c.Header("Content-Type", contentType)
}
c.Header("Content-Encoding", encoding)
c.Header("Vary", "Accept-Encoding")
c.Header("Content-Length", strconv.FormatInt(info.Size(), 10))
c.Status(http.StatusOK)
_, _ = io.Copy(c.Writer, file)
return true
}
func preferredEncoding(header string) string {
if header == "" {
return ""
}
accepted := make(map[string]bool, 4)
for _, part := range strings.Split(header, ",") {
token := strings.TrimSpace(strings.SplitN(part, ";", 2)[0])
accepted[strings.ToLower(token)] = true
}
switch {
case accepted["br"]:
return "br"
case accepted["gzip"]:
return "gzip"
default:
return ""
}
}
// compressedSuffix 把 Content-Encoding 映射到预压缩副本的扩展名(br / gz)。
func compressedSuffix(encoding string) string {
if encoding == "br" {
return "br"
}
return "gz"
}