go - 无法在标题中设置 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
[]
我读过类似的主题,但没有一个有效。
解决方案
您似乎没有使用有效的 cookie 名称。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
它提到=>
cookie 名称可以是除控制字符 (CTL)、空格或制表符之外的任何 US-ASCII 字符。它也不得包含如下分隔符: ( ) < > @ , ; : \ " / [ ] ? = { }。
如果您使用 cookie 名称,Name: "SpiderMan"
它应该可以工作。
推荐阅读
- python - 所以我必须写下一个返回形状的函数
- pdf - 修复页面底部页脚QWEB Invoice Report ODOO前的一个元素“DIV”
- php - 使用代码 eval("\$name= \"$input\";") 获取用户数据是否安全,其中 $input 从用户那里获取?
- php - 带有 ajax 的 CRUD SonataAdmin 在迁移之前不起作用
- cloudinary - Cloudinary 卡在 Displacement 上
- github - 在 GitHub 世界中,存储库的容器叫什么?
- sql - createQueryBuilder 和 setParameters() 为同一个参数多个值
- python - 在子目录中创建同名文件
- c++ - 将 char 指针传递给接受对 char 数组的引用的函数
- mysql - Rails Mysql 按关联表之一排序