Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting cookies with net/http

Tags:

cookies

go

I'm trying to set cookies with Go's net/http package. I have:

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

I tried googling 'Golang' with 'cookies', but didn't get any good results. If anyone can point me in the right direction it would be greatly appreciated.

like image 606
Tech163 Avatar asked Aug 26 '12 13:08

Tech163


People also ask

Can HTTP use cookies?

Typically, an HTTP cookie is used to tell if two requests come from the same browser—keeping a user logged in, for example. It remembers stateful information for the stateless HTTP protocol. Cookies are mainly used for three purposes: Session management.

How do I pass cookies in HTTP request?

To send cookies to the server, you need to add the "Cookie: name=value" header to your request. To send multiple Cookies in one cookie header, you can separate them with semicolons. In this Send Cookies example, we are sending HTTP cookies to the ReqBin echo URL.

How do I set cookies in API?

set() The set() method of the cookies API sets a cookie containing the specified cookie data. This method is equivalent to issuing an HTTP Set-Cookie header during a request to a given URL. The call succeeds only if you include the "cookies" API permission in your manifest.


2 Answers

I am not a Go expert, but I think you are setting the cookie on the request, aren't you? You might want to set it on the response. There is a setCookie function in net/http. This might help: http://golang.org/pkg/net/http/#SetCookie

func SetCookie(w ResponseWriter, cookie *Cookie) 
like image 66
Tobias N. Sasse Avatar answered Sep 23 '22 09:09

Tobias N. Sasse


//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 basic difference between Requests and ResponseWriter, a Request is what a browser will send like

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 a response is what the handler will send, something like :

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 will make a request, it'll include the cookie for that domain, since cookies are stored domain wise and can't be accessed from cross domains, if you set a cookie as HTTP only then it can only be accessed from the website which set it via HTTP and not via JS.

So when getting information from cookies you can do that from the r.Cookie method, like this

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 it in the response writer method, the request is a read only object which we respond to, think of it as a text message you get from someone, that is a request, you can only get it, what you type is a response, so you can type in a cookie at

for more details: https://thewhitetulip.gitbooks.io/webapp-with-golang-anti-textbook/content/content/2.4workingwithform.html

like image 23
thewhitetulip Avatar answered Sep 23 '22 09:09

thewhitetulip