如何读取cookie?

我从 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

我缺少的具体内容是什么?我想我混淆了 local/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)


白板的微信
浏览 147回答 1
1回答

慕虎7371278

例如,更好的方法是将您的 json 编码为 base64。我做了一个工作示例...主程序package mainimport (&nbsp; &nbsp; "encoding/base64"&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "io"&nbsp; &nbsp; "io/ioutil"&nbsp; &nbsp; "net/http")// Contains everything about an appointmenttype Appointment struct {&nbsp; &nbsp; Date&nbsp; &nbsp; string `json:"appointmentDate"`&nbsp; &nbsp; // Contains date as string&nbsp; &nbsp; StartMn string `json:"appointmentStartMn"` // Our startMn ?&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; int&nbsp; &nbsp; `json:"appointmentId"`&nbsp; &nbsp; &nbsp; // AppointmentId&nbsp; &nbsp; UserID&nbsp; int&nbsp; &nbsp; `json:"appointmentUserId"`&nbsp; // UserId}func main() {&nbsp; &nbsp; handler := http.NewServeMux()&nbsp; &nbsp; // Main request&nbsp; &nbsp; handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Requested /\r\n")&nbsp; &nbsp; &nbsp; &nbsp; // set typical headers&nbsp; &nbsp; &nbsp; &nbsp; w.Header().Set("Content-Type", "text/html")&nbsp; &nbsp; &nbsp; &nbsp; w.WriteHeader(http.StatusOK)&nbsp; &nbsp; &nbsp; &nbsp; // Read file&nbsp; &nbsp; &nbsp; &nbsp; b, _ := ioutil.ReadFile("index.html")&nbsp; &nbsp; &nbsp; &nbsp; io.WriteString(w, string(b))&nbsp; &nbsp; })&nbsp; &nbsp; // booking request&nbsp; &nbsp; handler.HandleFunc("/booking/", func(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Requested /booking/\r\n")&nbsp; &nbsp; &nbsp; &nbsp; // set typical headers&nbsp; &nbsp; &nbsp; &nbsp; w.Header().Set("Content-Type", "text/html")&nbsp; &nbsp; &nbsp; &nbsp; w.WriteHeader(http.StatusOK)&nbsp; &nbsp; &nbsp; &nbsp; // Read cookie&nbsp; &nbsp; &nbsp; &nbsp; cookie, err := r.Cookie("appointment")&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Cant find cookie :/\r\n")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s=%s\r\n", cookie.Name, cookie.Value)&nbsp; &nbsp; &nbsp; &nbsp; // Cookie data&nbsp; &nbsp; &nbsp; &nbsp; data, err := base64.StdEncoding.DecodeString(cookie.Value)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Error:", err)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; var appointment Appointment&nbsp; &nbsp; &nbsp; &nbsp; er := json.Unmarshal(data, &appointment)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("Error: ", er)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%s, %s, %d, %d\r\n", appointment.Date, appointment.StartMn, appointment.ID, appointment.UserID)&nbsp; &nbsp; &nbsp; &nbsp; // Read file&nbsp; &nbsp; &nbsp; &nbsp; b, _ := ioutil.ReadFile("booking.html")&nbsp; &nbsp; &nbsp; &nbsp; io.WriteString(w, string(b))&nbsp; &nbsp; })&nbsp; &nbsp; // Serve :)&nbsp; &nbsp; http.ListenAndServe(":8080", handler)}索引.html<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <title>Your page</title>&nbsp; &nbsp; </head><body>&nbsp; &nbsp; Setting cookie via Javascript&nbsp; &nbsp; <script type="text/javascript">&nbsp; &nbsp; window.onload = () => {&nbsp; &nbsp; &nbsp; &nbsp; function setCookie(name, value, days) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var expires = "";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (days) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var date = new Date();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; date.setTime(date.getTime() + (days*24*60*60*1000));&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; expires = "; expires=" + date.toUTCString();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.cookie = name + "=" + btoa((value || ""))&nbsp; + expires + "; path=/";&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; setCookie("appointment", JSON.stringify({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appointmentDate: "20-01-2019 13:06",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appointmentStartMn: "1-2",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appointmentId: 2,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appointmentUserId: 3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; &nbsp; &nbsp; );&nbsp; &nbsp; &nbsp; &nbsp; document.location = "/booking/";&nbsp; &nbsp; }&nbsp; &nbsp; </script></body>预订.html<html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <title>Your page</title>&nbsp; &nbsp; </head><body>&nbsp; &nbsp; Your booking is okay :)</body>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go