net/http 包
1func handler(w http.ResponseWriter, r _http.Request) {
2 w.Header().Set("Access-Control-Allow-Origin", "_")
3}
gin 包
gin/cros
导入包
1import (
2 "github.com/gin-contrib/cors"
3 "github.com/gin-gonic/gin"
4)
设置跨域中间件
1r.Use(cors.Default())
自定义中间件
1// 设置跨域请求的中间件
2r.Use(func(c *gin.Context) {
3 c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
4 c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
5 c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, Authorization")
6 if c.Request.Method == "OPTIONS" {
7 c.AbortWithStatus(204)
8 return
9 }
10 c.Next()
11})