Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up Cookies at browser : Golang

As am newbie here on Golang, trying to setup cookies at browser, have simple basic code but it doesn't working at all & did some googling & found some stackoverflow ex. but still not picking up the right way.

Created a simple hello.go

package main

import "io"
import "net/http"
import "time"

func handler(w http.ResponseWriter, req *http.Request) {
    expire := time.Now().AddDate(0, 0, 1)
    cookie := http.Cookie{"test", "tcookie", "/", "www.dummy.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("/", handler)
}

But as expected here am facing error's like \hello.go:9:15: composite struct literal net/http.Cookie with untagged fields

Could any one please suggest me or give me basic example (in detailing) for setting up cookies.

Had few searches on SO and found.. Setting Cookies in Golang (net/http) but not able to picking up this properly..

Thanks.

like image 641
eegloo Avatar asked Jun 13 '13 11:06

eegloo


Video Answer


2 Answers

Well in the question you link to it basically says to use this function from net/http:

func SetCookie(w ResponseWriter, cookie *Cookie)

So in your example instead of writing

req.AddCookie(&cookie)

you should write this

http.SetCookie(w, &cookie)
like image 122
stephanos Avatar answered Sep 28 '22 06:09

stephanos


cookie := http.Cookie{"test", "tcookie", "/", "www.dummy.com", expire, expire.Format(time.UnixDate), 86400, true, true, "test=tcookie", []string{"test=tcookie"}}

should be something like this:

cookie := &http.Cookie{Name:"test", Value:"tcookie", Expires:time.Now().Add(356*24*time.Hour), HttpOnly:true}

after this

change

req.AddCookie(&cookie)

to

http.SetCookie(w, cookie)

and finally because your application is running on Google App Engine change:

func main()

to

func init()

like image 31
Neo Avatar answered Sep 28 '22 07:09

Neo