0
1

Go言語におけるCORS設定の実装方法

Posted at

Go言語でHTTPサーバを実装する際にCORS(Cross-Origin Resource Sharing)の設定を行う方法。

※CORS:ウェブアプリケーションが異なるオリジンのリソースを安全にリクエストできるようにする仕組み

CORSミドルウェアの実装

CORSポリシーを実施するミドルウェア関数を定義。(今回は全てのHTTPレスポンスに適切なCORSヘッダーを追加し、プリフライトリクエストに適切に応答するものとして定義している)

presentation/cors_middleware.go
package presentation

import "net/http"

func CORSMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*")
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")

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

        next.ServeHTTP(w, r)
    })
}

CORSミドルウェアの適用

HTTPハンドラーに定義したCORSミドルウェアを適応。

...
corsHandler := CORSMiddleware(proxyHandler)
    http.Handle(config.Path, corsHandler)
...

今回ドメイン駆動設計をアーキテクチャに実装してるものとして、presentation層に実装した。
(どのドメインからのアクセスを許可するかというHTTPレベルのセキュリティポリシーの管理、presentation層の責務!)

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1