1 回答
TA贡献1802条经验 获得超4个赞
例如,更好的方法是将您的 json 编码为 base64。我做了一个工作示例...
主程序
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)
}
索引.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>
预订.html
<html>
<head>
<title>Your page</title>
</head>
<body>
Your booking is okay :)
</body>
- 1 回答
- 0 关注
- 146 浏览
添加回答
举报