无法在标题中设置Cookie

abh*_*jan 1 cookies go

我正在尝试从Go Web服务器设置cookie,然后在chrome浏览器中读取它。

这是我的代码

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()
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在chrome浏览器中获取cookie时,从调用set_cookies设置cookie后,我得到以下输出:

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

[]
Run Code Online (Sandbox Code Playgroud)

我读过类似的主题,但没有一个奏效。

Abh*_*t_K 5

看来您没有使用有效的cookie名称。 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie

它提到=>

Cookie名称可以是除控制字符(CTL),空格或制表之外的任何US-ASCII字符。它还不能包含如下分隔符:()<> @,; :\“ / []?= {}。

如果您使用cookie名称,因为Name: "SpiderMan"它应该可以工作。