r.Request.cookie()不起作用,如果我使用r.Response.request(),它会出现错误。

huangapple go评论62阅读模式
英文:

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

huangapple
  • 本文由 发表于 2022年4月11日 04:01:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/71820122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定