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.
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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With