2023-06-15 21:22:51 +08:00
|
|
|
//
|
|
|
|
// cors.go
|
|
|
|
// Copyright (C) 2022 tiglog <me@tiglog.com>
|
|
|
|
//
|
|
|
|
// Distributed under terms of the MIT license.
|
|
|
|
//
|
|
|
|
|
2023-10-17 17:21:14 +08:00
|
|
|
package cors
|
2023-06-15 21:22:51 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
|
|
|
|
2023-06-15 21:38:12 +08:00
|
|
|
"git.hexq.cn/tiglog/golib/helper"
|
2023-10-17 17:21:14 +08:00
|
|
|
"github.com/gin-gonic/gin"
|
2023-06-15 21:22:51 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
func NewCors(origins []string) gin.HandlerFunc {
|
|
|
|
return func(c *gin.Context) {
|
|
|
|
method := c.Request.Method
|
|
|
|
origin := c.Request.Header.Get("Origin")
|
|
|
|
if helper.InStringSlice(origin, origins) {
|
|
|
|
c.Header("Access-Control-Allow-Origin", origin)
|
|
|
|
c.Header("Access-Control-Allow-Headers", "Content-Type,X-CSRF-Token, Authorization")
|
|
|
|
c.Header("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PUT")
|
|
|
|
c.Header("Access-Control-Expose-Headers", "Content-Length, Content-Type")
|
|
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
|
|
}
|
|
|
|
|
|
|
|
// 放行所有OPTIONS方法
|
|
|
|
if method == "OPTIONS" {
|
|
|
|
c.AbortWithStatus(http.StatusNoContent)
|
|
|
|
}
|
|
|
|
// 处理请求
|
|
|
|
c.Next()
|
|
|
|
}
|
|
|
|
}
|