golib/middleware/cors.go
2023-06-15 21:38:12 +08:00

37 lines
909 B
Go

//
// cors.go
// Copyright (C) 2022 tiglog <me@tiglog.com>
//
// Distributed under terms of the MIT license.
//
package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"git.hexq.cn/tiglog/golib/helper"
)
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()
}
}