56 lines
2.0 KiB
Go
56 lines
2.0 KiB
Go
package lxcors
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
func Cors() gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
method := c.Request.Method
|
|
|
|
//origin := c.Request.Header.Get("Origin")
|
|
//fmt.Println("origin----", origin)
|
|
var headerKeys []string
|
|
for k, _ := range c.Request.Header {
|
|
headerKeys = append(headerKeys, k)
|
|
}
|
|
headerStr := strings.Join(headerKeys, ", ")
|
|
if headerStr != "" {
|
|
headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, Content-Type, %s", headerStr)
|
|
} else {
|
|
headerStr = "access-control-allow-origin, access-control-allow-headers"
|
|
}
|
|
headerStr += "access-control-allow-origin, access-control-allow-headers, Content-Type,token"
|
|
//var origins = []string{"https://www.qizhangfang.com", "https://wx.qizhangfang.net", "https://qizhangfang.com", "http://www.qizhangfang.com", "http://qizhangfang.com",
|
|
// "http://192.168.3.153:8000", "http://localhost:8000"} // 允许跨域
|
|
//fmt.Println(origins)
|
|
//if origin != "" {
|
|
//
|
|
//
|
|
//}
|
|
|
|
//下面的都是乱添加的-_-~
|
|
//c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
|
|
|
//c.Header("Access-Control-Allow-Origin", ogn)
|
|
c.Header("Access-Control-Allow-Origin", "*")
|
|
c.Header("Access-Control-Allow-Headers", headerStr)
|
|
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
|
|
// c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma")
|
|
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type, Token, token")
|
|
// c.Header("Access-Control-Max-Age", "172800")
|
|
c.Header("Access-Control-Allow-Credentials", "true")
|
|
c.Set("content-type", "application/json")
|
|
|
|
//放行所有OPTIONS方法
|
|
if method == "OPTIONS" {
|
|
c.JSON(http.StatusOK, "Options Request!")
|
|
}
|
|
|
|
c.Next()
|
|
}
|
|
}
|