2
1

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 5 years have passed since last update.

Goでhttp.Redirectを使用した時SetCookieが無視されてしまう

Posted at

事象

いつもコードを書く時に見た目がスッキリするので画面表示と内部の処理を別のメソッドで書いていたのですが
Cookieを使用する際にsetCookieの後http.redirectを使用したらCookieが登録できていなかったというものです。

ダメだったコード

main.go

package main

import (
	"html/template"
	"net/http"
)

func main(){
    server := http.Server{
        Addr: "localhost:8080",
    }

    http.HandleFunc("/set", setCookie)
    http.HandleFunc("/cookieComp", cookieCompleteHandler)

    server.ListenAndServe()
}

func setCookie(w http.ResponseWriter, r *http.Request) {
    cookie := &http.Cookie{
        Name: "Taro",
        Value: "たなかたろうです!",
    }

    http.SetCookie(w, cookie)

    http.Redirect(w, r, "/cookieComp", http.StatusFound)
}

func cookieCompleteHandler(w http.ResponseWriter, r *http.Request){
    var templatefile = template.Must(template.ParseFiles("./cookieComplete.html"))
	templatefile.Execute(w, "cookieComplete.html")
}

cookieComplete.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>team</title>
    </head>
    <body>
        <p>cookie</p>
        <p> name: {{.Name}} </p>
        <p> value:{{.Value}} </p>
    </body>
</html>

正しいコード

main.go

package main

import (
	"html/template"
	"net/http"
)

func main(){
    server := http.Server{
        Addr: "localhost:8080",
    }

    http.HandleFunc("/set", setCookie)

    server.ListenAndServe()
}

func setCookie(w http.ResponseWriter, r *http.Request) {
    cookie := &http.Cookie{
        Name: "Taro",
        Value: "たなかたろうです!",
    }

    http.SetCookie(w, cookie)

    tmpl := template.Must(template.ParseFiles("./cookieComplete.html"))
    tmpl.Execute(w, &cookie)
}

cookieComplete.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>team</title>
    </head>
    <body>
        <p>cookie</p>
        <p> name: {{.Name}} </p>
        <p> value:{{.Value}} </p>
    </body>
</html>

実行

runした後にlocalhost:8080/setで動きます!

2
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?