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

在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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符