func ShowAllTasksFunc(w http.ResponseWriter, r *http.Request){
if r.Method == "GET" {
context := db.GetTasks("pending")
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,*
处理程序将发送响应,例如:
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