Files
OpenList/server/middlewares.go

38 lines
1.3 KiB
Go
Raw Normal View History

2020-12-24 01:39:45 +08:00
package server
import (
2020-12-24 20:25:40 +08:00
"github.com/Xhofe/alist/conf"
2021-01-11 16:53:48 +08:00
"github.com/Xhofe/alist/server/controllers"
2021-01-08 16:32:02 +08:00
"github.com/Xhofe/alist/utils"
2020-12-24 01:39:45 +08:00
"github.com/gin-gonic/gin"
)
2021-02-04 10:02:34 +08:00
// handle cors request
func CorsHandler() gin.HandlerFunc {
2020-12-24 01:39:45 +08:00
return func(context *gin.Context) {
2021-03-05 21:25:44 +08:00
origin := context.GetHeader("Origin")
2021-01-12 14:58:33 +08:00
// 同源
if origin == "" {
context.Next()
return
}
2020-12-24 01:39:45 +08:00
method := context.Request.Method
2021-01-08 16:32:02 +08:00
// 设置跨域
2021-03-05 21:25:44 +08:00
context.Header("Access-Control-Allow-Origin", origin)
2020-12-24 01:39:45 +08:00
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
2021-01-11 16:53:48 +08:00
context.Header("Access-Control-Allow-Headers", "Content-Length,session,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language, Keep-Alive, User-Agent, Cache-Control, Content-Type")
context.Header("Access-Control-Expose-Headers", "Content-Length,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified")
2020-12-24 01:39:45 +08:00
context.Header("Access-Control-Max-Age", "172800")
2021-01-11 16:53:48 +08:00
// 信任域名
2021-03-05 21:25:44 +08:00
if conf.Conf.Server.SiteUrl != "*" && utils.ContainsString(conf.Origins, context.GetHeader("Origin")) == -1 {
context.JSON(200, controllers.MetaResponse(413, "The origin is not in the site_url list, please configure it correctly."))
2021-01-11 16:53:48 +08:00
context.Abort()
}
2020-12-24 01:39:45 +08:00
if method == "OPTIONS" {
2021-01-11 16:53:48 +08:00
context.AbortWithStatus(204)
2020-12-24 01:39:45 +08:00
}
//处理请求
context.Next()
}
2021-03-05 21:25:44 +08:00
}