Jal
Jal

Reputation: 2312

Cannot see cookie in chrome inspect application cookie after setting cookie in golang server

Here is a simplify version of my golang server.

package main

import (
    "fmt"
    "net/http"
    "log"
    "time"
)

func sayhelloName(w http.ResponseWriter, r *http.Request) {

    fmt.Fprintf(w, "Hello name!") // send data to client side
    expiration := time.Now().Add(365 * 24 * time.Hour)
    cookie := http.Cookie{Name: "username", Value: "myusernmae", Expires: expiration}
    http.SetCookie(w, &cookie)
    cookie = http.Cookie{Name: "username2", Value: "myusernmae", Expires: expiration}
    http.SetCookie(w, &cookie)

}

func main() {
    http.HandleFunc("/", sayhelloName) // set router
    err := http.ListenAndServe(":9090", nil) // set listen port
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

I am trying to set a cookie to the client. But after hitting http://localhost:9090/ I don't see the cookie name: username I set.

Am I doing the cookie setting correct?

Upvotes: 2

Views: 581

Answers (1)

Shiva Kishore
Shiva Kishore

Reputation: 1701

func sayhelloName(w http.ResponseWriter, r *http.Request) {

   expiration := time.Now().Add(365 * 24 * time.Hour)
   cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
   http.SetCookie(w, &cookie)
   cookie = http.Cookie{Name: "username2", Value: "astaxie", Expires: expiration}
   http.SetCookie(w, &cookie)
   fmt.Fprintf(w, "Hello name!") // send data to client side
}

you should send data to client only after setting the cookie

Upvotes: 3

Related Questions