使用net / http设置cookie


76

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

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”进行谷歌搜索,但未获得任何良好结果。如果有人能指出我正确的方向,将不胜感激。

Answers:


95

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

func SetCookie(w ResponseWriter, cookie *Cookie)

1
谢谢。这似乎有效。我被错误地看着golang.org/pkg/net/http/#Request.AddCookie更早
Tech163

12
是的,这令人困惑。如果go程序充当HTTP客户端,并且想向HTTP服务器发送cookie值,则需要Request.AddCookie ...
Tobias N. Sasse 2012年

您能否说明如何创建和设置Cookie?
亚历山大·米尔斯

15
//ShowAllTasksFunc is used to handle the "/" URL which is the default ons
func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request){
    if r.Method == "GET" {
        context := db.GetTasks("pending") //true when you want non deleted notes
        if message != "" {
            context.Message = message
        }
        context.CSRFToken = "abcd"
        message = ""
        expiration := time.Now().Add(365 * 24 * time.Hour)
        cookie    :=    http.Cookie{Name: "csrftoken",Value:"abcd",Expires:expiration}
        http.SetCookie(w, &cookie)
        homeTemplate.Execute(w, context)
    } else {
        message = "Method not allowed"
        http.Redirect(w, r, "/", http.StatusFound)
    }
}

Requests和之间有一个基本区别ResponseWriter,请求是浏览器将发送的内容

Host: 127.0.0.1:8081
User-Agent: ...
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://127.0.0.1:8081/
Cookie: csrftoken=abcd
Connection: keep-alive

处理程序将发送响应,例如:

Content-Type: text/html; charset=utf-8
Date: Tue, 12 Jan 2016 16:43:53 GMT
Set-Cookie: csrftoken=abcd; Expires=Wed, 11 Jan 2017 16:43:53 GMT
Transfer-Encoding: chunked
<html>...</html>

当浏览器发出请求时,它将包含该域的cookie,因为cookie是按域存储的,并且不能从跨域访问,如果将cookie设置为仅HTTP,则只能从cookie进行访问。通过HTTP而非JS进行设置的网站。

因此,从Cookie获取信息时,您可以通过r.Cookie方法执行此操作

cookie, _ := r.Cookie("csrftoken")
if formToken == cookie.Value {

https://github.com/thewhitetulip/Tasks/blob/master/views/addViews.go#L72-L75

但是,当您要设置Cookie时,必须在响应编写器方法中进行操作,该请求是我们响应的只读对象,将其视为您从某人处获得的短信,即请求,您只能得到它,您键入的是一个响应,因此您可以在以下位置输入Cookie

有关更多详细信息:https : //thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html


1
在我的情况下,没有设置路径就无法设置Cookie:http.Cookie{Name: "csrftoken",Value:"abcd",Expires:expiration, Path: "/"}
Maxim Yefremov


6

下面显示了我们如何在产品中使用cookie:

func handleFoo(w http.ResponseWriter, r *http.Request) {

    // cookie will get expired after 1 year 
    expires := time.Now().AddDate(1, 0, 0)

    ck := http.Cookie{
        Name: "JSESSION_ID",
        Domain: "foo.com",
        Path: "/",
        Expires: expires,
    }

    // value of cookie    
    ck.Value = "value of this awesome cookie"

    // write the cookie to response
    http.SetCookie(w, &ck)

    // ...
}

5

在我添加Path和MaxAge之前,它在Safari中不起作用。安全和常规Cookie都对我有用

分享,这样可以帮助像我这样停留超过2天的人:)

expire := time.Now().Add(20 * time.Minute) // Expires in 20 minutes
cookie := http.Cookie{Name: "username", Value: "nonsecureuser", Path: "/", Expires: expire, MaxAge: 86400}
http.SetCookie(w, &cookie)
cookie = http.Cookie{Name: "secureusername", Value: "secureuser", Path: "/", Expires: expire, MaxAge: 86400, HttpOnly: true, Secure: true}
http.SetCookie(w, &cookie)

1
谢谢,这对我也起作用,只走了一条路就够了
CommonSenseCode

谢谢deepakssn!你是救世主!
考斯

4

首先,您需要创建Cookie,然后使用http包的SetCookie()函数来设置Cookie。

expire := time.Now().Add(10 * time.Minute) 
cookie := http.Cookie{Name: "User", Value: "John", Path: "/", Expires: expire, MaxAge: 90000}
http.SetCookie(w, &cookie)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.