abhishek ranjan
abhishek ranjan

Reputation: 652

Not able to set cookies in header

I am trying to set cookies from Go web server and then reading it in the chrome browser.

Here is my code

package main

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


func setCookies(w http.ResponseWriter, r *http.Request){
    expiration := time.Now().Add(365 * 24 * time.Hour)
    c1 := http.Cookie{Name: "SpiderMan: Far from home",Value : "HollyWood", Path: "/", Expires: expiration, Secure: false}
    http.SetCookie(w,&c1)
    c2 := http.Cookie{Name: "Kabir Singh",Value: "BollyWood", Path: "/", Expires: expiration, Secure: false}
    http.SetCookie(w,&c2)

    // w.Header().Set("Set-Cookie",c1.String())
    // w.Header().Add("Set-Cookie",c2.String())
    // HttpOnly: true

    fmt.Fprintf(w, "")

}

func getCookies(w http.ResponseWriter, r *http.Request){
    // h := r.Header["Kabir Singh"]
    // fmt.Fprintln(w,h)

    c1, err := r.Cookie("Kabir Singh")
    if err != nil {
        fmt.Fprintln(w, "first_cookie is not set successfully." ,err)
    }
    ca := r.Cookies()
    fmt.Fprintln(w, c1)
    fmt.Fprintln(w, ca)
}

func main() {
    server := http.Server{
        Addr: "127.0.0.1:2020",
    }
    http.HandleFunc("/set_cookies", setCookies)
    http.HandleFunc("/get_cookies", getCookies)
    server.ListenAndServe()
}

After setting the cookies from call set_cookies when I am trying to get the cookies in the chrome browser I get this output:

first_cookie is not set successfully. http: named cookie not present

[]

I have read similar threads but none of it worked.

Upvotes: 1

Views: 105

Answers (2)

WiththeWind
WiththeWind

Reputation: 153

The problem you are having is caused by the name of your cookie. Adjust the names to not have whitespace and they will work as expected.

Example:

c2 := http.Cookie{Name: "Kabir-Singh", Value: "BollyWood", Path: "/", Expires: expiration, Secure: false}

http.SetCookie(w, &c2)

Upvotes: 2

Abhijit-K
Abhijit-K

Reputation: 3689

It appears that you are not using valid cookie name. https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

It mentions =>

A cookie-name can be any US-ASCII characters except control characters (CTLs), spaces, or tabs. It also must not contain a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }.

if you use cookie name as just Name: "SpiderMan" it should work.

Upvotes: 5

Related Questions