duanbipu1720
2018-01-26 20:08
浏览 179
已采纳

在Golang服务器中设置Cookie后,无法在Chrome检查应用程序Cookie中看到Cookie

Here is a simplify version of my golang server.

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)
    }
}

I am trying to set a cookie to the client. But after hitting http://localhost:9090/ I don't see the cookie name: username I set.

Am I doing the cookie setting correct?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • duanqiang6501 2018-01-26 20:17
    最佳回答
    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
    }
    

    you should send data to client only after setting the cookie

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题