github.com/wfusion/gofusion@v1.1.14/http/middleware/cors.go (about)

     1  package middleware
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"strings"
     7  
     8  	"github.com/gin-gonic/gin"
     9  )
    10  
    11  func Cors() gin.HandlerFunc {
    12  	return func(c *gin.Context) {
    13  		origin := c.Request.Header.Get("Origin")
    14  		var headerKeys []string
    15  		for k := range c.Request.Header {
    16  			headerKeys = append(headerKeys, k)
    17  		}
    18  		corsHeader := c.GetHeader("Access-Control-Request-Headers")
    19  		headerKeys = append(headerKeys, strings.Split(corsHeader, ",")...)
    20  
    21  		headerStr := strings.Join(headerKeys, ", ")
    22  		if headerStr != "" {
    23  			headerStr = fmt.Sprintf("access-control-allow-origin, access-control-allow-headers, %s", headerStr)
    24  		} else {
    25  			headerStr = "access-control-allow-origin, access-control-allow-headers"
    26  		}
    27  		if origin != "" {
    28  			c.Writer.Header().Set("Access-Control-Allow-Origin", origin)
    29  			c.Writer.Header().Set("Access-Control-Allow-Headers", headerStr)
    30  			c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT, DELETE")
    31  			c.Writer.Header().Set("Access-Control-Expose-Headers",
    32  				"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
    33  			c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
    34  		}
    35  
    36  		if c.Request.Method == "OPTIONS" {
    37  			c.AbortWithStatusJSON(http.StatusNoContent, "no content")
    38  		}
    39  		c.Next()
    40  	}
    41  }