[golang ]在 Golang 中處理 CORS(跨來源資源共享, Cross-Origin Resource Sharing)

 在 Golang 中處理 CORS(跨來源資源共享, Cross-Origin Resource Sharing),通常會用 Gin 或 net/http 來實現,這樣可以確保你的 API 可以被前端或其他服務安全地訪問。以下是幾種處理 CORS 的方式。


1. 使用 Gin 處理 CORS

如果你是用 Gin 框架,可以透過 github.com/gin-contrib/cors 這個套件來簡單設定 CORS 規則。

安裝 cors 套件

go get github.com/gin-contrib/cors


在 Gin 設定 CORS

package main
import ( "github.com/gin-contrib/cors""github.com/gin-gonic/gin""time" ) funcmain() { r := gin.Default() // 設定 CORS 規則 r.Use(cors.New(cors.Config{ AllowOrigins: []string{"http://localhost:3000", "https://example.com"}, // 允許的來源 AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, // 允許的方法 AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, // 允許的標頭 ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, // 是否允許攜帶憑證(cookies) MaxAge: 12 * time.Hour, // 預檢請求的緩存時間 })) // 定義 API 路由 r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{"message": "pong"}) }) // 啟動服務 r.Run(":8080") }

這樣你的 API 就可以允許來自 http://localhost:3000 和 https://example.com 的請求!



2. 在 net/http 中手動處理 CORS

如果你是用標準的 net/http,可以自己寫一個 CORS 中介函式(middleware) 來手動控制允許的請求來源。

在 net/http 設定 CORS

package main
import ( "fmt""net/http" ) // CORS 處理函式funcenableCORS(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "http://localhost:3000") // 允許的來源 w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") // 允許的方法 w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization") // 允許的標頭 w.Header().Set("Access-Control-Allow-Credentials", "true") // 允許攜帶憑證(如 Cookies)// 若是 OPTIONS 預檢請求,直接回應 200if r.Method == "OPTIONS" { w.WriteHeader(http.StatusOK) return } } // 處理請求的 handlerfunchandler(w http.ResponseWriter, r *http.Request) { enableCORS(w, r) fmt.Fprintf(w, "CORS 設定成功!") } funcmain() { http.HandleFunc("/", handler) fmt.Println("Server is running on port 8080...") http.ListenAndServe(":8080", nil) }

💡 這樣就可以讓 http://localhost:3000 訪問你的 API!



3. CORS 預檢請求(OPTIONS)

當前端發送 跨域請求(例如 POSTPUT、攜帶 Authorization 的請求) 時,瀏覽器會先發送一個 OPTIONS 預檢請求,確認伺服器是否允許該請求。

如果 CORS 沒有正確設置,會出現類似:

Accessto XMLHttpRequest at 'http://localhost:8080/'from origin 'http://localhost:3000' has been blocked by CORS policy

你可以手動處理 OPTIONS

if r.Method == "OPTIONS" {
    w.WriteHeader(http.StatusOK)
    return
}

這樣預檢請求會回應 200 OK,瀏覽器就能繼續發送真正的請求了。



4. 在 Nginx 處理 CORS(適用於反向代理)

如果你的 Go API 是透過 Nginx 代理,可以直接在 Nginx 設定 CORS:

server {
listen80; server_name example.com; location / { proxy_pass http://localhost:8080; add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"; add_header Access-Control-Allow-Headers "Content-Type, Authorization"; if ($request_method = OPTIONS) { return200; } } }

這樣 所有跨域請求 都會被允許,適合 API 伺服器。



5. CORS 安全建議

  1. 不要使用 * 作為 Access-Control-Allow-Origin,應該明確設定允許的來源,避免安全風險。
  2. 允許 OPTIONS 預檢請求,否則前端可能無法正常發送 POST 或 PUT 請求。
  3. 在 AllowCredentials 設為 true 時,Allow-Origin 不能是 *,否則瀏覽器會拒絕請求。


留言

這個網誌中的熱門文章

[Kotlin]如何學習Kotlin

[golang]如何使用 gorm 高效執行批量插入 (可以透過 Create()、CreateInBatches(),或者 原生 SQL 語句 來提升效率)

[Kotlin]Kotlin Multiplatform (KMP) 如何安裝使用和部署