//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) } }
There is a major difference between Requests and ResponseWriter , the request is what the browser will send, for example
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
and the response will be sent by the handler, for example:
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>
When the browser completes the request, it will contain a cookie for this domain, since cookies are stored in the domain and cannot be accessed from cross domains, if you set the cookie as HTTP only then it can only be accessed from the website that sets it through HTTP, not through JS.
Therefore, when you receive information from cookies, you can do this from the r.Cookie method, for example,
cookie, _ := r.Cookie("csrftoken") if formToken == cookie.Value {
https://github.com/thewhitetulip/Tasks/blob/master/views/addViews.go#L72-L75
But when you are going to set a cookie, you have to do this in the response recording method, the request is a read-only object that we are responding to, think of it as a text message that you receive from someone, a request you can receive its only, what you enter is the answer, so you can enter a cookie in
for more details: https://thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html