Takeshi Yamada
Takeshi Yamada

Reputation: 3

Cookie can't be set.

I defined two handler functions, setCookie and getCookie. The first function, setCookie, is called by getting access to localhost:8080/set_cookie, and then sends a HTTP response including two cookies. The other function, getCookie, is called by accessing to localhost:8080/get_cookie, and then gets Cookie object. I expect getCookie function to show information about two cookies, but a message, "first_cookie is not set successfully", is shown on a web browser.

Do you have any idea solving this problem?

package main

import (
    "fmt"
    "net/http"
)

func setCookie(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "setCookie called")
    c1 := http.Cookie{
        Name:     "first_cookie",
        Value:    "Go Web App",
        HttpOnly: true,
    }
    c2 := http.Cookie{
        Name:     "second_cookie",
        Value:    "Another service",
        HttpOnly: true,
    }
    http.SetCookie(w, &c1)
    http.SetCookie(w, &c2)
}

func getCookie(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "getCookie called")
    c1, err := r.Cookie("first_cookie")
    if err != nil {
        fmt.Fprintln(w, "first_cookie is not set successfully.")
    }
    ca := r.Cookies()
    fmt.Fprintln(w, c1)
    fmt.Fprintln(w, ca)
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:8080",
    }
    http.HandleFunc("/set_cookie", setCookie)
    http.HandleFunc("/get_cookie", getCookie)
    server.ListenAndServe()
}

Upvotes: 0

Views: 1315

Answers (1)

billf
billf

Reputation: 112

Your debugging statement...

fmt.Fprintln(w, "setCookie called")

... occurs before your http.SetCookie call.

Cookies are set in headers but by writing to the http.ReponseWriter you've triggered the completion of setting any headers. If you move the debug statement to the last line of setCookie, it will work as expected.

You can trivially test this by running:

curl -v -c "cookie.jar" "http://localhost:8080/set_cookie"

before and after such a change.

Upvotes: 4

Related Questions