我正在尝试从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
[]
我读过类似的主题,但是没有一个起作用。
答案 0 :(得分:5)
似乎您没有使用有效的cookie名称。 https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
它提到=>
cookie名称可以是任何US-ASCII字符,但控制字符(CTL),空格或制表符除外。它还不能包含如下分隔符:()<> @,; :\“ / []?= {}。
如果您将cookie名称仅用作vstack
,它应该可以使用。
答案 1 :(得分:2)
您遇到的问题是由Cookie的名称引起的。调整名称以使其没有空格,它们将按预期工作。
示例:
c2 := http.Cookie{Name: "Kabir-Singh", Value: "BollyWood", Path: "/", Expires: expiration, Secure: false}
http.SetCookie(w, &c2)