2012-08-26 38 views
53

我试图用Golang的net/http设置cookie。我有在Golang中设置Cookie(net/http)

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

我试着用'cookies'搜索googling'Golang',但没有得到任何好结果。如果任何人都可以指出我正确的方向,将不胜感激。

谢谢。

回答

68

我不是Go专家,但我认为你在请求中设置了Cookie,是不是。您可能希望将其设置为响应。 net/http中有一个setCookie函数。这可能帮助: http://golang.org/pkg/net/http/#SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie) 
+1

谢谢。这似乎工作。我错误地看着http://golang.org/pkg/net/http/#Request.AddCookie早些时候 – Tech163

+8

是的,它很混乱。如果您的go程序充当HTTP客户端并且您想要将cookie值发送到HTTP服务器,那么您需要Request.AddCookie ... –

5

这下面的代码可以帮助ü

cookie1 := &http.Cookie{Name: "sample", Value: "sample", HttpOnly: false} 
    http.SetCookie(w, cookie1) 
8
//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) 
    } 
} 

RequestsResponseWriter之间的基本区别,一个请求是什么浏览器就会发出像

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只能作为HTTP,它只能从通过HTTP设置它的网站访问,而不能通过JS访问。

因此,从饼干获取信息时,你可以做到这一点从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

2

下面展示了我们如何使用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) 

    // ... 
} 
0

它不是为我工作在Safari中,直到我添加了Path和MaxAge。安全和常规饼干为我工作

共享,以便它可以帮助别人谁卡住像我要超过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) 
0

首先,您需要创建的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)