github.com/isyscore/isc-gobase@v1.5.3-0.20231218061332-cbc7451899e9/server/cors.go (about)

     1  package server
     2  
     3  import (
     4  	"log"
     5  	"net/http"
     6  
     7  	"github.com/gin-gonic/gin"
     8  )
     9  
    10  // Cors 配置允许跨域请求
    11  func Cors() gin.HandlerFunc {
    12  	return func(c *gin.Context) {
    13  		method := c.Request.Method
    14  		origin := c.Request.Header.Clone().Get("Origin")
    15  		if origin != "" {
    16  			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
    17  			c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
    18  			c.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session")
    19  			c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers")
    20  			c.Header("Access-Control-Max-Age", "172800")
    21  			c.Header("Access-Control-Allow-Credentials", "true")
    22  		}
    23  		//允许类型校验
    24  		if method == "OPTIONS" {
    25  			c.JSON(http.StatusOK, "ok!")
    26  		}
    27  		defer func() {
    28  			if err := recover(); err != nil {
    29  				log.Printf("跨域中断: %v\n", err)
    30  			}
    31  		}()
    32  		c.Next()
    33  	}
    34  }