HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Setting cookies with net/http from the server

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
netwithfromtheservercookiessettinghttp

Problem

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.

Solution

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)

Code Snippets

func SetCookie(w ResponseWriter, cookie *Cookie)

Context

Stack Overflow Q#12130582, score: 122

Revisions (0)

No revisions yet.