使用net / http设置cookie [英] Setting cookies with net/http

查看:185
本文介绍了使用net / http设置cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Go的net / http软件包设置Cookie。我有:

I'm trying to set cookies with Go's net/http package. I have:

package main

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

func indexHandler(w http.ResponseWriter, req *http.Request) {
    expire := time.Now().AddDate(0, 0, 1)
    cookie := http.Cookie{"test", "tcookie", "/", "www.domain.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("/", indexHandler)
    http.ListenAndServe(":80", nil)
}

我尝试将 Golang与 cookies进行谷歌搜索,但没有得到任何良好的结果。如果有人能向我指出正确的方向,将不胜感激。

I tried googling 'Golang' with 'cookies', but didn't get any good results. If anyone can point me in the right direction it would be greatly appreciated.

推荐答案

我不是Go专家,但我认为您是在请求中设置Cookie,不是吗?您可能要在响应上进行设置。 net / http中有一个 setCookie 函数。这可能会有所帮助:
http://golang.org/pkg/net/http/ #SetCookie

I am not a Go expert, but I think you are setting the cookie on the request, aren't you? You might want to set it on the response. There is a setCookie function in net/http. This might help: http://golang.org/pkg/net/http/#SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie)

这篇关于使用net / http设置cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆