如何读取cookies?

Ado*_*Ren 6 cookies go

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

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

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

window.location.href = "https://localhost:8080/booking/"
Run Code Online (Sandbox Code Playgroud)

setCookie 函数:

function setCookie(cookieName, cookieValue) {
    document.cookie = `${cookieName}=${cookieValue};secure;`;
}
Run Code Online (Sandbox Code Playgroud)

我想从我的 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
Run Code Online (Sandbox Code Playgroud)

我缺少的具体是什么?我想我混淆了本地/http cookie 但如何实现客户端设置 cookie 的读取?

更新(有关更多信息,请参阅答案)

和 golang 没有关系。我的:

appointmentDate: selectedDay.date
Run Code Online (Sandbox Code Playgroud)

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

所以这成功了:

`${cookieName}=${encodeURIComponent(cookieValue)};secure;` + "path=/";`
Run Code Online (Sandbox Code Playgroud)

在 go 中(为了节省空间,这里没有发现错误):

cookie, _ := r.Cookie("appointment")
data, _ := url.QueryUnescape(cookie.Value)
Run Code Online (Sandbox Code Playgroud)

Seb*_*uer 8

例如,更好的方法是将您的 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)
}

Run Code Online (Sandbox Code Playgroud)

索引.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>
Run Code Online (Sandbox Code Playgroud)

预订.html

<html>
    <head>
        <title>Your page</title>
    </head>
<body>
    Your booking is okay :)
</body>
Run Code Online (Sandbox Code Playgroud)