//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,那么它只能从通过 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时,你必须在response writer方法中做,请求是一个我们响应的只读对象,把它想象成你从某人那里得到的短信,那是一个请求,你只能得到它,你输入的是一个响应,所以你可以在
更多详情:https ://thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html