背景
跨域一般有兩種方法:
- 網絡代理層,如nginx層攔截處理;
- 后端服務處理;
這里簡單說下Go Gin框架的解決辦法
解決方法
需要在 Gin 中提供了 middleware (中間件) 來處理請求前后的前置和后置邏輯。
中間件文件:
package middleware
import (
"github.com/gin-gonic/gin"
"net/http"
)
func Cors() gin.HandlerFunc {
return func(c *gin.Context) {
method := c.Request.Method
origin := c.Request.Header.Get("Origin") //請求頭部
if origin != "" {
//接收客戶端發送的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")
//允許客戶端傳遞校驗信息比如 cookie (重要)
c.Header("Access-Control-Allow-Credentials", "true")
//
//c.Header("Content-Type", "application/json")
}
//允許類型校驗
if method == "OPTIONS" {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization") //自定義 Header
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
c.Header("Access-Control-Allow-Credentials", "true")
c.AbortWithStatus(http.StatusNoContent)
}
defer func() {
if err := recover(); err != nil {
log.Printf("Panic info is: %v", err)
}
}()
c.Next()
}
}
應用中間件:
package main
import(
"gin/middleware"
"github.com/gin-gonic/gin"
)
func main(){
gin.SetMode(gin.ReleaseMode)
engine = gin.Default()
engine.Use(middleware.Cors())
}
