2012-08-26 67 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)