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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!