[golang]Golang 設定 CORS 規則

 

Golang 設定 CORS 規則 (AllowOrigins)

在 Golang 的 gin 框架中,你可以使用 github.com/gin-contrib/cors 來設定 CORS(跨來源資源共享)。

 AllowOrigins 設定

  • AllowOrigins 設定的是允許請求的來源網址
  • 當你使用 Postman 測試時,應該設定為 "*" 或 ["http://localhost"]


 CORS 設定範例

package main
import ( "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" "time" ) func main() { r := gin.Default() // 設定 CORS r.Use(cors.New(cors.Config{ AllowOrigins: []string{"*"}, // 允許所有來源 (Postman 可以使用) AllowMethods: []string{"GET", "POST", "PUT", "DELETE"}, AllowHeaders: []string{"Origin", "Content-Type", "Authorization"}, ExposeHeaders: []string{"Content-Length"}, AllowCredentials: true, MaxAge: 12 * time.Hour, // 預先請求快取 12 小時 })) r.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "CORS 設定成功!"}) }) r.Run(":8080") }


AllowOrigins 設定解析

設定值適用情境說明
AllowOrigins: []string{"*"}適用於 Postman 或測試環境允許任何網域發送請求
AllowOrigins: []string{"http://localhost"}適用於本機開發只允許 http://localhost 的請求
AllowOrigins: []string{"http://example.com"}限制為特定網域只允許 example.com 來源的請求


Postman 測試

  1. 開啟 Postman
  2. 設定請求
    • 方法GET
    • 網址http://localhost:8080/
  3. 送出請求
  4. 確認回應:json複製編輯{ "message": "CORS 設定成功!" }


 結論

  • Postman 不會受到 CORS 限制,但如果你用瀏覽器發 AJAX 請求,則需要正確設定 AllowOrigins
  • 開發環境 (localhost):設定 AllowOrigins: []string{"http://localhost"}
  • 允許所有來源(測試用):設定 AllowOrigins: []string{"*"}


留言

這個網誌中的熱門文章

[Kotlin]如何學習Kotlin

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

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