【问题标题】:How to read cookies?如何读取 cookie?
【发布时间】:2019-01-20 10:51:26
【问题描述】:

我从 javascript 中设置了一个 cookie,例如:

setCookie("appointment", JSON.stringify({
                appointmentDate: selectedDay.date,
                appointmentStartMn: appointment.mnRange[0],
                appointmentId: appointment.id || 0,
                appointmentUserId: appointment.user.id || 0
          })
);

设置 cookie 后,我想将用户重定向到预订页面:

window.location.href = "https://localhost:8080/booking/"

setCookie 函数:

function setCookie(cookieName, cookieValue) {
    document.cookie = `${cookieName}=${cookieValue};secure;`;
}

我想从我的 go 后端检索那个 cookie,但我不知道该怎么做。由于我以前从未使用过 cookie,因此我已经阅读过这个问题,但答案似乎表明除了设置 document.cookie 之外我不需要做太多事情。

在我的浏览器存储中,我可以看到 cookie 确实按预期设置。

在我的 Go 后端我想打印 cookie:

r.HandleFunc("/booking/", handler.serveTemplate)

func (handler *templateHandler) serveTemplate(w http.ResponseWriter, r *http.Request) {
    c, err := r.Cookie("appointment")
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println(c.Value)
    }
}

//output http: named cookie not present

我缺少什么?我想我对本地/http cookie 感到困惑,但是如何实现读取客户端设置的 cookie?

更新(查看答案了解更多)

与golang无关。我的:

appointmentDate: selectedDay.date

2019-01-01- 的格式不是可以发送到后端的有效字符。它可以在我的浏览器中使用,但需要进行 URI 编码才能传递。

这样就成功了:

`${cookieName}=${encodeURIComponent(cookieValue)};secure;` + "path=/";`

并且在运行中(这里没有发现错误以节省空间):

cookie, _ := r.Cookie("appointment")
data, _ := url.QueryUnescape(cookie.Value)

【问题讨论】:

  • 您是否尝试将 cookie 的域设置为空字符串?例如。 cookieName=cookieValue;domain=;secure;?
  • 刚试过。没有成功。
  • 当您删除 ;secure 并重定向到 http 而不是 https 时,这甚至无需指定空域即可工作,至少在 firefox 上对我有用。但是,您正在重定向到默认情况下本地主机不支持的 https,因此无论您使用什么来支持它,例如代理,可能是导致 cookie 丢失的原因。
  • 我用随机 cookie 尝试了一些愚蠢的东西,它可以工作(甚至是安全的)。请参阅更新的答案。现在不知道在哪里看,但可能我的“约会”cookie 有缺陷。
  • 好像是这样,我之前尝试过,但在整个 cookie 上。 (我要求恩典,新手)。我可以将一些东西传递给我的后端! :)

标签: go cookies


【解决方案1】:

例如,更好的方法是将您的 json 编码为 base64。我做了一个工作示例...

main.go

package main

import (
    "encoding/base64"
    "encoding/json"
    "fmt"
    "io"
    "io/ioutil"
    "net/http"
)

// Contains everything about an appointment
type Appointment struct {
    Date    string `json:"appointmentDate"`    // Contains date as string
    StartMn string `json:"appointmentStartMn"` // Our startMn ?
    ID      int    `json:"appointmentId"`      // AppointmentId
    UserID  int    `json:"appointmentUserId"`  // UserId
}

func main() {
    handler := http.NewServeMux()

    // Main request
    handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Requested /\r\n")

        // set typical headers
        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)

        // Read file
        b, _ := ioutil.ReadFile("index.html")
        io.WriteString(w, string(b))
    })

    // booking request
    handler.HandleFunc("/booking/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Requested /booking/\r\n")

        // set typical headers
        w.Header().Set("Content-Type", "text/html")
        w.WriteHeader(http.StatusOK)

        // Read cookie
        cookie, err := r.Cookie("appointment")
        if err != nil {
            fmt.Printf("Cant find cookie :/\r\n")
            return
        }

        fmt.Printf("%s=%s\r\n", cookie.Name, cookie.Value)

        // Cookie data
        data, err := base64.StdEncoding.DecodeString(cookie.Value)
        if err != nil {
            fmt.Printf("Error:", err)
        }

        var appointment Appointment
        er := json.Unmarshal(data, &appointment)
        if err != nil {
            fmt.Printf("Error: ", er)
        }

        fmt.Printf("%s, %s, %d, %d\r\n", appointment.Date, appointment.StartMn, appointment.ID, appointment.UserID)

        // Read file
        b, _ := ioutil.ReadFile("booking.html")
        io.WriteString(w, string(b))
    })

    // Serve :)
    http.ListenAndServe(":8080", handler)
}

index.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Setting cookie via Javascript

    <script type="text/javascript">
    window.onload = () => {
        function setCookie(name, value, days) {
            var expires = "";
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days*24*60*60*1000));
                expires = "; expires=" + date.toUTCString();
            }
            document.cookie = name + "=" + btoa((value || ""))  + expires + "; path=/";
        }

        setCookie("appointment", JSON.stringify({
                    appointmentDate: "20-01-2019 13:06",
                    appointmentStartMn: "1-2",
                    appointmentId: 2,
                    appointmentUserId: 3
            })
        );

        document.location = "/booking/";
    }
    </script>
</body>

booking.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Your booking is okay :)
</body>

【讨论】:

  • 感谢您在答案中投入的时间。为什么说 base64 是更好的方法?
  • 正如mkopriva 已经提到的,您的cookie 中有一些“非法”字符。您可以使用任何序列化方法,例如 base64 或 encode 来消除这些字符。
  • 我验证你的回答。您指出我的数据包含非法字符。事实上,日期。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 2015-11-25
  • 2022-01-10
相关资源
最近更新 更多