在golang服务器中设置cookie后,无法在chrome检查应用程序cookie中看到cookie

时间:2018-01-26 20:08:30

标签: go cookies

这是我的golang服务器的简化版本。

package main

import (
    "fmt"
    "net/http"
    "log"
    "time"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {

    fmt.Fprintf(w, "Hello name!") // send data to client side
    expiration := time.Now().Add(365 * 24 * time.Hour)
    cookie := http.Cookie{Name: "username", Value: "myusernmae", Expires: expiration}
    http.SetCookie(w, &cookie)
    cookie = http.Cookie{Name: "username2", Value: "myusernmae", Expires: expiration}
    http.SetCookie(w, &cookie)

}

func main() {
    http.HandleFunc("/", sayhelloName) // set router
    err := http.ListenAndServe(":9090", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

我正在尝试为客户端设置cookie。但是在点击http://localhost:9090/后,我没有看到我设置的Cookie name: username

我是否正确设置Cookie设置?

1 个答案:

答案 0 :(得分:3)

func sayhelloName(w http.ResponseWriter, r *http.Request) {

   expiration := time.Now().Add(365 * 24 * time.Hour)
   cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
   http.SetCookie(w, &cookie)
   cookie = http.Cookie{Name: "username2", Value: "astaxie", Expires: expiration}
   http.SetCookie(w, &cookie)
   fmt.Fprintf(w, "Hello name!") // send data to client side
}

只有在设置cookie后才能将数据发送到客户端