diff --git a/web/deeplx_handler.go b/web/deeplx_handler.go index eae8962..7ab0e37 100644 --- a/web/deeplx_handler.go +++ b/web/deeplx_handler.go @@ -34,5 +34,28 @@ func (d *DeepLXHandler) Translate(c *gin.Context) { } func (d *DeepLXHandler) RegisterRoutes(engine *gin.Engine) { + engine.Use(Cors()) engine.POST(d.routePath, d.Translate) } + +// Cors 跨域中间件 +func Cors() gin.HandlerFunc { + return func(c *gin.Context) { + origin := c.Request.Header.Get("Origin") + if origin != "" { + c.Header("Access-Control-Allow-Origin", origin) + c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS") + c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Authorization, X-Requested-With") + c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers") + c.Header("Access-Control-Max-Age", "86400") // 24 hours + c.Header("Access-Control-Allow-Credentials", "true") + } + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(http.StatusNoContent) + return + } + + c.Next() + } +}