Go中跨域Cors中間件的實現(xiàn)
通過建造者模式創(chuàng)建我們的跨域中間件Cors
我們了解到,當使用XMLHttpRequest發(fā)送請求時,如果瀏覽器發(fā)現(xiàn)違反了同源策略就會自動加上一個請求頭 origin;
后端在接受到請求后確定響應后會在 Response Headers 中加入一個屬性 Access-Control-Allow-Origin;
瀏覽器判斷響應中的 Access-Control-Allow-Origin 值是否和當前的地址相同,匹配成功后才繼續(xù)響應處理,否則報錯
缺點:忽略 cookie,瀏覽器版本有一定要求
同時,結合項目實際,我們可以使用一個config結構體來存放我們的配置,這里可以使用建造者模式進行靈活的管理
所以cors中,我們也添加與config相同的字段
Config:
// CorsConfig 使用了建造者模式 type CorsConfig struct { AllowOrigins []string AllowMethods []string AllowHeaders []string //如果想要讓客戶端可以訪問到其他的標頭,服務器必須將它們在 Access-Control-Expose-Headers 里面列出來.eg:"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires ExposeHeaders []string //這個響應頭表示 preflight request (預檢請求)的返回結果(即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息)可以被緩存多久。 AccessControlMaxAge string //告知瀏覽器是否可以將對請求的響應暴露給前端 JavaScript 代碼。 AccessControlAllowCredentials bool }
Cors:
type Cors struct { AllowOrigins []string AllowMethods []string AllowHeaders []string //如果想要讓客戶端可以訪問到其他的標頭,服務器必須將它們在 Access-Control-Expose-Headers 里面列出來.eg:"Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires ExposeHeaders []string //這個響應頭表示 preflight request (預檢請求)的返回結果(即 Access-Control-Allow-Methods 和Access-Control-Allow-Headers 提供的信息)可以被緩存多久。 AccessControlMaxAge string //告知瀏覽器是否可以將對請求的響應暴露給前端 JavaScript 代碼。 AccessControlAllowCredentials bool }
當然,我們的Config需要一些方法來控制字段的值
func (c *CorsConfig) AddOrigins(origins ...string) *CorsConfig { c.AllowOrigins = append(c.AllowOrigins, origins...) return c } func (c *CorsConfig) AddMethods(methods ...string) *CorsConfig { c.AllowMethods = append(c.AllowMethods, methods...) return c } func (c *CorsConfig) AddHeaders(headers ...string) *CorsConfig { c.AllowHeaders = append(c.AllowHeaders, headers...) return c } func (c *CorsConfig) AddExposeHeaders(exposeHeaders ...string) *CorsConfig { c.ExposeHeaders = append(c.ExposeHeaders, exposeHeaders...) return c } func (c *CorsConfig) SetAccessControlMaxAge(ms string) *CorsConfig { c.AccessControlMaxAge = ms return c } func (c *CorsConfig) SetAccessControlAllowCredentials(isAllow bool) *CorsConfig { c.AccessControlAllowCredentials = isAllow return c }
同時,為了方便,我們可以給出一個方法來設置默認的情況
func DefaultCorsConfig() *CorsConfig { return &CorsConfig{ AllowOrigins: []string{"*"}, AllowMethods: []string{"POST", "POST", "GET", "OPTIONS", "PUT", "DELETE", "UPDATE"}, AllowHeaders: []string{"Authorization", "Content-Length", "X-CSRF-Token", "Token", "session", "X_Requested_With", "Accept", "Origin", "Host", "Connection", "Accept-Encoding", "Accept-Language", "DNT", "X-CustomHeader", "Keep-Alive", "User-Agent", "X-Requested-With", "If-Modified-Since", "Cache-Control", "Content-Type", "Pragma"}, ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Cache-Control", "Content-Languge", "Caontent-Type", "Expires", "Last-Modified", "Pragma", "FooBar"}, AccessControlMaxAge: "200000", AccessControlAllowCredentials: true, } }
最后,實現(xiàn)將config應用到Cors中的方法和應用Cors的設置的方法
將config應用到Cors中的方法:
func (cors *Cors) SetCorsConfig(c *CorsConfig) { cors.AccessControlMaxAge = c.AccessControlMaxAge cors.ExposeHeaders = c.ExposeHeaders cors.AllowOrigins = c.AllowOrigins cors.AllowHeaders = c.AllowHeaders cors.AllowMethods = c.AllowMethods cors.AccessControlAllowCredentials = c.AccessControlAllowCredentials }
應用Cors的設置的方法 :
func (cors *Cors) Apply() sgin8.HandlerFunc { return func(context *sgin8.Context) { method := context.Req.Method origin := context.Req.Header.Get("Origin") if origin != "" { context.SetHeader("Access-Control-Allow-Origin", strings.Join(cors.AllowOrigins, ",")) // 設置允許訪問所有域 context.SetHeader("Access-Control-Allow-Methods", strings.Join(cors.AllowMethods, ",")) context.SetHeader("Access-Control-Allow-Headers", strings.Join(cors.AllowHeaders, ",")) context.SetHeader("Access-Control-Expose-Headers", strings.Join(cors.ExposeHeaders, ",")) context.SetHeader("Access-Control-Max-Age", cors.AccessControlMaxAge) context.SetHeader("Access-Control-Allow-Credentials", strconv.FormatBool(cors.AccessControlAllowCredentials)) } else { log.Printf("This request haven not set the 'Origin' in Header") } if method == "OPTIONS" { context.JSON(http.StatusOK, "Options Request!") } //處理請求 context.Next() } }
當然,我們提供快速開始的方案:
func (c *CorsConfig) Build() sgin8.HandlerFunc { cors := &Cors{} cors.SetCorsConfig(c) return cors.Apply() }
demo:
func main() { //eg1: r := sgin8.Default() config1 := sgin8.DefaultCorsConfig() cors1 := sgin8.Cors{} cors1.SetCorsConfig(config1) r.Use(cors1.Apply()) //eg2 r.Use(sgin8.DefaultCorsConfig().Build()) //eg3 config3 := sgin8.CorsConfig{} config3.SetAccessControlMaxAge("200000").SetAccessControlAllowCredentials(true).AddMethods("GET", "POST") r.Use(config3.Build()) //eg4 config4 := &sgin8.CorsConfig{} config4.SetAccessControlMaxAge("200000").SetAccessControlAllowCredentials(true).AddMethods("GET", "POST") cors4 := sgin8.Cors{} cors4.SetCorsConfig(config4) cors4.Apply() r.GET("/", func(c *sgin8.Context) { c.String(http.StatusOK, "Hello wxk\n") }) // index out of range for testing Recovery() r.GET("/panic", func(c *sgin8.Context) { names := []string{"wxk"} c.String(http.StatusOK, names[100]) //訪問不到 }) r.Run(":9999") }
你也許會問為什么實現(xiàn)的這么繁瑣,那么下文將會解釋下原因!
外鏈:http://chabaoo.cn/article/237709.htm
跨域測試:
失敗情況:
成功情況!
到此這篇關于Go中跨域Cors中間件的實現(xiàn)的文章就介紹到這了,更多相關Go跨域Cors中間件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
golang獲取prometheus數(shù)據(jù)(prometheus/client_golang包)
本文主要介紹了使用Go語言的prometheus/client_golang包來獲取Prometheus監(jiān)控數(shù)據(jù),具有一定的參考價值,感興趣的可以了解一下2025-03-03Go實現(xiàn)替換(覆蓋)文件某一行內(nèi)容的示例代碼
本文主要介紹了Go實現(xiàn)替換(覆蓋)文件某一行內(nèi)容的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07