duanquan4451 2013-06-13 11:34
浏览 197
已采纳

在浏览器中设置Cookie:Golang

As am newbie here on Golang, trying to setup cookies at browser, have simple basic code but it doesn't working at all & did some googling & found some stackoverflow ex. but still not picking up the right way.

Created a simple hello.go

package main

import "io"
import "net/http"
import "time"

func handler(w http.ResponseWriter, req *http.Request) {
    expire := time.Now().AddDate(0, 0, 1)
    cookie := http.Cookie{"test", "tcookie", "/", "www.dummy.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}
    req.AddCookie(&cookie)
    io.WriteString(w, "Hello world!")
}

func main() {
    http.HandleFunc("/", handler)
}

But as expected here am facing error's like \hello.go:9:15: composite struct literal net/http.Cookie with untagged fields

Could any one please suggest me or give me basic example (in detailing) for setting up cookies.

Had few searches on SO and found.. Setting Cookies in Golang (net/http) but not able to picking up this properly..

Thanks.

  • 写回答

2条回答 默认 最新

  • dongzh1988 2013-06-13 11:42
    关注

    Well in the question you link to it basically says to use this function from net/http:

    func SetCookie(w ResponseWriter, cookie *Cookie)
    

    So in your example instead of writing

    req.AddCookie(&cookie)
    

    you should write this

    http.SetCookie(w, &cookie)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置