0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Go】http.ResponseWriterのメソッドw.Header().Add()が効かない

Posted at

http.ResponseWriterのメソッドHeader().Add()でヘッダーを追加したはずなのに、レスポンスのヘッダーを見ると付与されていない。

単純にw.Header().Addの前に、w.Writeを呼び出していたことが原因だった。順番を逆にすると、想定どおり動作する。

改修前
func(w http.ResponseWriter, _ *http.Request) {
	w.Write([]byte("Hello, world"))

	w.Header().Add("Access-Control-Allow-Origin", "http://localhost:3000")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token")
	w.Header().Add("Access-Control-Allow-Methods", "POST, OPTIONS")
	w.Header().Add("Access-Control-Expose-Headers", "X-CSRF-Token")
	w.Header().Add("Access-Control-Allow-Credentials", "true")
}
改修後
func(w http.ResponseWriter, _ *http.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "http://localhost:3000")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token")
	w.Header().Add("Access-Control-Allow-Methods", "POST, OPTIONS")
	w.Header().Add("Access-Control-Expose-Headers", "X-CSRF-Token")
	w.Header().Add("Access-Control-Allow-Credentials", "true")

	w.Write([]byte("Hello, world"))
}
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?