chore: initial commit of HouseholdBudgetBook (backend, frontend, desktop)
This commit is contained in:
commit
4a5db3f1f9
167 files changed
+21732
No files matched your search
@@ -0,0 +1,57 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func Setup(r *gin.Engine, mode string, corsOrigins string) {
|
||||
r.Use(gin.CustomRecovery(func(c *gin.Context, err any) {
|
||||
slog.Error("panic recovered", "error", err, "path", c.Request.URL.Path)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "服务器内部错误"})
|
||||
}))
|
||||
|
||||
origins := parseCORSOrigins(corsOrigins, mode)
|
||||
if len(origins) > 0 {
|
||||
r.Use(cors.New(cors.Config{
|
||||
AllowOrigins: origins,
|
||||
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||||
AllowHeaders: []string{"Origin", "Content-Type", "Accept"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: 12 * time.Hour,
|
||||
}))
|
||||
}
|
||||
|
||||
r.Use(gin.LoggerWithFormatter(func(params gin.LogFormatterParams) string {
|
||||
slog.Info("request",
|
||||
"method", params.Method,
|
||||
"path", params.Path,
|
||||
"status", params.StatusCode,
|
||||
"latency", params.Latency.String(),
|
||||
)
|
||||
return ""
|
||||
}))
|
||||
}
|
||||
|
||||
func parseCORSOrigins(raw, mode string) []string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
if mode == "dev" {
|
||||
return []string{"http://localhost:5173", "http://127.0.0.1:5173"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(raw, ",")
|
||||
out := make([]string, 0, len(parts))
|
||||
for _, p := range parts {
|
||||
if v := strings.TrimSpace(p); v != "" {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
Reference in new issue
Block a user