構成

  • GCP ApiGateway -> CloudRun
  • ApiGateway で OpenAPI yaml を定義している

1. OpenAPI yaml で x-google-endpoints に allowCors: True を設定して、バックエンドでCORSリクエストを処理する

x-google-endpoints:
  - name: ${managed_service}
    allowCors: True # バックエンドでCORSリクエストを処理する

2. CloudRun で OPTIONS メソッドを設定する

// 以下のように cors ミドルウェアを挟む
http.HandleFunc("/example", cors(user.Handler))
// 定義はこんな感じ
func cors(next http.HandlerFunc) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        if r.Method == "OPTIONS" {
            slog.Info("==> Reply OPTIONS Request", "status", http.StatusNoContent)
            w.Header().Set("Access-Control-Allow-Origin", "*")
            w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
            w.Header().Set("Access-Control-Allow-Headers", "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization")
            w.Header().Set("Access-Control-Expose-Headers", "Content-Length,Content-Range")
            w.Header().Set("Access-Control-Max-Age", "1728000") // 20 days: reduce preflight requests
            w.WriteHeader(http.StatusNoContent)                 // 204
            return
        }
        next.ServeHTTP(w, r)
    }
}

Refs