go - 如何阅读Cookie?

标签 go cookies

我从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确实已按预期设置。
在我的后端中,我要打印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)

最佳答案

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

关于go - 如何阅读Cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62829616/

相关文章:

java - cookie.setMaxAge 奇怪的行为

Go channel 和延迟

go - 为 ARM 构建?设置 GOBIN 后无法使用 `go install` 进行交叉编译

go - 连接到 Click to Deploy Cassandra 实例的问题

go - 具有返回值的go函数

forms - 为什么在表单提交中传递Google Analytics(分析)值?

javascript - 从电子邮件访问 cookie?

html - 在 cookie 中存储 OAuth token 是不好的做法吗?

image - 如何在 Go 中为图像添加简单的文本标签?

javascript - 从 Firefox 扩展 (XUL) 读取网页 cookie