12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package middleware
- import (
- "io/ioutil"
- "net/http"
- "path/filepath"
- "runtime"
- "gitee.com/xuyiping_admin/pkg/logger/zaplog"
- "go.uber.org/zap"
- "github.com/gin-contrib/cors"
- "github.com/gin-gonic/gin"
- )
- func CORS(configs ...cors.Config) gin.HandlerFunc {
- if len(configs) != 0 {
- return cors.New(configs[0])
- }
- return func(c *gin.Context) {
- method := c.Request.Method
- origin := c.Request.Header.Get("Origin")
- if origin != "" {
-
- c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
-
- c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
-
- c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
-
- c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
-
- c.Header("Access-Control-Max-Age", "172800")
-
- c.Header("Access-Control-Allow-Credentials", "true")
- }
-
- if method == "OPTIONS" {
- c.JSON(http.StatusOK, "ok!")
- return
- }
- defer func() {
- if err := recover(); err != nil {
- body, _ := ioutil.ReadAll(c.Request.Body)
-
- pc, file, line, ok := runtime.Caller(1)
- funcName := ""
- if ok {
- funcName := runtime.FuncForPC(pc).Name()
-
- funcName = filepath.Base(funcName)
- file = filepath.Base(file)
- }
- zaplog.Error("cors",
- zap.Any("recover", err),
- zap.Any("url", c.Request.URL),
- zap.Any("method", method),
- zap.Any("file", file),
- zap.Any("line", line),
- zap.Any("func", funcName),
- zap.Any("request", string(body)),
- )
- }
- }()
- c.Next()
- }
- }
|