命名的 cookie 不存在

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

Named cookie not present

问题

我正在构建一个依赖于 cookie 的网站。然后我决定编写一个函数来设置一个 cookie,然后读取同一个 cookie,以便查看浏览器是否允许使用 cookie。但是这个方法失败了。

./views/index.html 中的模板代码如下:

{{define "index"}}template{{end}}

主要代码如下:

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"

	"strconv"
	"time"

	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

var tmpl *template.Template

func main() {
	port := ":8088"
	router := mux.NewRouter()
	router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// 设置测试 cookie
		cookieName := strconv.FormatInt(time.Now().UnixNano(), 10)
		cookieValue := strconv.FormatInt(time.Now().UnixNano(), 10)

		fmt.Println("cookieName:" + cookieName)
		fmt.Println("cookieValue:" + cookieValue)
		cookie := http.Cookie{Name: cookieName, Value: cookieValue, Path: "/"}
		http.SetCookie(w, &cookie)

		// 获取 cookie
		fmt.Println("Range over cookies")
		for _, c := range r.Cookies() {
			fmt.Println(c)
		}

		// 根据名称获取测试 cookie
		c, err := r.Cookie(cookieName)
		if err != nil {
			fmt.Println("Error: " + err.Error())
		} else {
			fmt.Println(c.Value)
		}

		err = tmpl.ExecuteTemplate(w, "index", "")
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
		}
	})

	var err error
	tmpl, err = template.ParseGlob("views/*")
	if err != nil {
		panic(err.Error())
	}

	router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
		http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
	})

	fmt.Println("Server running on localhost" + port)

	err = http.ListenAndServe(port, handlers.CompressHandler(router))
	if err != nil {
		log.Fatal(err)
	}
}

终端输出如下:

Server running on localhost:8088
cookieName:1636243636497412077
cookieValue:1636243636497413613
Range over cookies
Error: http: named cookie not present

有什么问题的指针可以提供给我吗?

英文:

I am building a website that will rely on cookies for various things.
Then I decided to have a function that sets a cookie then read the same cookie in order to see if the browser allows cookies.
But this fails.

The template in ./views/index.html

{{define "index"}}template{{end}}

The main code:

package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var tmpl *template.Template
func main(){
port :=":8088"
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//Set test cookie
cookieName := strconv.FormatInt(time.Now().UnixNano(), 10)
cookieValue := strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Println("cookieName:" + cookieName)
fmt.Println("cookieValue:" + cookieValue)
cookie := http.Cookie{Name: cookieName, Value: cookieValue, Path: "/"}
http.SetCookie(w, &cookie)
//Get cookies
fmt.Println("Range over cookies")
for _, c := range r.Cookies() {
fmt.Println(c)
}
//Get test cookie by name
c, err := r.Cookie(cookieName)
if err != nil {
fmt.Println("Error: " + err.Error())
} else {
fmt.Println(c.Value)
}
err = tmpl.ExecuteTemplate(w, "index", "")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
var err error
tmpl, err = template.ParseGlob("views/*")
if err != nil {
panic(err.Error())
}
router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
})
fmt.Println("Server running on localhost" + port)
err = http.ListenAndServe(port, handlers.CompressHandler(router))
if err != nil {
log.Fatal(err)
}
}

This is terminal output:

Server running on localhost:8088
cookieName:1636243636497412077
cookieValue:1636243636497413613
Range over cookies
Error: http: named cookie not present

Any pointers to what my issue might be?

答案1

得分: 3

你在发送 cookie 给客户端之前检查了 r.Cookies。你必须先发送 cookie,然后如果你想要检查他们的 cookie,发送第二个请求。在发送第一个响应后,直接打开浏览器查看你的 cookie 是否存在会更容易一些。

英文:

You are checking r.Cookies before you have sent the cookie to the client. You must send the cookie and then if you want to check their cookie, send a second request. It would be much easier to just open the browser and look to see if your cookie is there after you send your first response.

答案2

得分: 1

方法Request.Cookie从请求的Cookieheaders中获取一个cookie。

函数http.SetCookie将Set-Cookie头添加到响应headers中。您可以使用以下代码观察http.SetCookie的结果:

 fmt.Println(w.Header()["Set-Cookie"])

由于http.SetCookie不会修改当前请求,因此当前请求中没有指定的cookie。

cookie值的流程如下:

  1. 服务器使用Set-Cookie头在响应中设置cookie。
  2. 客户端将cookie存储在“cookie jar”中。
  3. 客户端使用Cookie请求头从jar中添加匹配的cookie到请求中。
  4. 服务器从请求headers中获取cookie。

尝试以下代码。在浏览器中加载页面并刷新以观察cookie值的流程。

    const cookieName = "example"
cookieValue := strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Printf("Set cookie %s=%s\n", cookieName, cookieValue)
cookie := http.Cookie{Name: cookieName, Value: cookieValue, Path: "/"}
http.SetCookie(w, &cookie)
c, err := r.Cookie(cookieName)
if err != nil {
fmt.Printf("Get cookie %s error: %v\n", cookieName, err)
} else {
fmt.Printf("Get cookie %s=%s\n", cookieName, c.Value)
}
英文:

The method Request.Cookie gets a cookie from request Cookie headers.

The function http.SetCookie adds a Set-Cookie header to the response headers. You can observe the result of http.SetCookie using this code:

 fmt.Println(w.Header()["Set-Cookie"])

The named cookie is not present in the current request because http.SetCookie does not modify the current request.

The flow of cookie values is this:

  1. The server sets cookies in a response using the Set-Cookie header.
  2. The client stores the cookies in a "cookie jar".
  3. The client adds matching cookies from the jar to requests using the Cookie request header.
  4. The server gets the cookies form the request headers.

Try this code. Load the page in the browser and refresh to observe the flow of cookie values.

    const cookieName = "example"
cookieValue := strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Printf("Set cookie %s=%s\n", cookieName, cookieValue)
cookie := http.Cookie{Name: cookieName, Value: cookieValue, Path: "/"}
http.SetCookie(w, &cookie)
c, err := r.Cookie(cookieName)
if err != nil {
fmt.Printf("Get cookie %s error: %v\n", cookieName, err)
} else {
fmt.Printf("Get cookie %s=%s\n", cookieName, c.Value)
}

huangapple
  • 本文由 发表于 2021年11月7日 08:10:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/69868884.html
匿名

发表评论

匿名网友

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

确定