首页 > 解决方案 > 无法在标题中设置 cookie

问题描述

我正在尝试从 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()
}

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

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

[]

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

标签: gocookies

解决方案


您似乎没有使用有效的 cookie 名称。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie

它提到=>

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

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


推荐阅读