英文:
r.Request.cookie() not working and if I use r.Response.request() it panic
问题
首先,我不知道最近的Go更新是否不再与r.Request.Cookie()函数一起使用,但似乎这个函数不再存在了。
所以我找到了r.Response.Request.Cookie(),但是一旦我打开页面,它就崩溃了。
这是我的代码:
package main
import (
	"io"
	"log"
	"net/http"
	uuid "github.com/nu7hatch/gouuid"
)
func main() {
	r := http.NewServeMux()
	r.HandleFunc("/", index)
	http.ListenAndServe(":80", r)
}
func index(w http.ResponseWriter, req *http.Request) {
	c, err := req.Response.Request.Cookie("session-id")
	if err != nil {
		cid, _ := uuid.NewV4()
		c := &http.Cookie{
			Name:  "session-id",
			Value: cid.String(),
		}
		http.SetCookie(w, c)
	}
	log.Fatal(err)
	io.WriteString(w, c.String())
}
希望对你有帮助!
英文:
First I don't know if recent updates of go doesn't work anymore with r.Request.Cookie() but it seems that this func doesn't exist anymore...
So I came across r.Response.Request.Cookie() but as soon as I open the page it crash.
This is my code:
package main
import (
	"io"
	"log"
	"net/http"
	uuid "github.com/nu7hatch/gouuid"
)
func main() {
	r := http.NewServeMux()
	r.HandleFunc("/", index)
	http.ListenAndServe(":80", r)
}
func index(w http.ResponseWriter, req *http.Request) {
	c, err := req.Response.Request.Cookie("session-id")
	if err != nil {
		cid, _ := uuid.NewV4()
		c := &http.Cookie{
			Name:  "session-id",
			Value: cid.String(),
		}
		http.SetCookie(w, c)
	}
	log.Fatal(err)
	io.WriteString(w, c.String())
}
答案1
得分: 1
在c, err := req.Response.Request.Cookie("session-id")中,Request将为nil,因为它已经被使用过了,你可以直接使用req.Cookie("cookie-name")。
英文:
In c, err := req.Response.Request.Cookie("session-id") The Request will be nil as it's already consumed, You can go with req.Cookie("cookie-name") directly.
答案2
得分: 0
我正在为你提供中文翻译,以下是翻译好的内容:
我观看的教程可能已经过时了。更新后的可用代码如下:
cookie, err := req.Cookie("session-id")
if err == http.ErrNoCookie {
c := &http.Cookie{
    Name:     "session-id",
    Value:    cid.String(),
    MaxAge:   300,
    HttpOnly: true,
}
感谢所有回答的人。
英文:
The tutorial I was whatching was likely outdated. The updated working code is:
cookie, err := req.Cookie("session-id")
if err == http.ErrNoCookie {
c := &http.Cookie{
    Name:     "session-id",
    Value:    cid.String(),
    MaxAge:   300,
    HttpOnly: true,
}
Thanks for everyone that answered
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论