我正在建立一個網站,該網站將依賴 cookie 來處理各種事情。然后我決定有一個函式來設定 cookie 然后讀取相同的 cookie 以查看瀏覽器是否允許 cookie。但這失敗了。
./views/index.html 中的模板
{{define "index"}}template{{end}}
主要代碼:
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
var tmpl *template.Template
func main(){
port :=":8088"
router := mux.NewRouter()
router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
//Set test cookie
cookieName := strconv.FormatInt(time.Now().UnixNano(), 10)
cookieValue := strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Println("cookieName:" cookieName)
fmt.Println("cookieValue:" cookieValue)
cookie := http.Cookie{Name: cookieName, Value: cookieValue, Path: "/"}
http.SetCookie(w, &cookie)
//Get cookies
fmt.Println("Range over cookies")
for _, c := range r.Cookies() {
fmt.Println(c)
}
//Get test cookie by name
c, err := r.Cookie(cookieName)
if err != nil {
fmt.Println("Error: " err.Error())
} else {
fmt.Println(c.Value)
}
err = tmpl.ExecuteTemplate(w, "index", "")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
var err error
tmpl, err = template.ParseGlob("views/*")
if err != nil {
panic(err.Error())
}
router.PathPrefix("/").HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
http.FileServer(http.Dir("./static/")).ServeHTTP(res, req)
})
fmt.Println("Server running on localhost" port)
err = http.ListenAndServe(port, handlers.CompressHandler(router))
if err != nil {
log.Fatal(err)
}
}
這是終端輸出:
Server running on localhost:8088
cookieName:1636243636497412077
cookieValue:1636243636497413613
Range over cookies
Error: http: named cookie not present
任何指向我的問題可能是什么的指標?
uj5u.com熱心網友回復:
在將 cookie 發送到客戶端之前,您正在檢查 r.Cookies。您必須發送 cookie,然后如果您想檢查他們的 cookie,請發送第二個請求。在您發送第一個回應后,打開瀏覽器并查看您的 cookie 是否存在會容易得多。
uj5u.com熱心網友回復:
Request.Cookie方法從請求 Cookie標頭中獲取 cookie 。
函式http.SetCookie添加一個 Set-Cookie 頭到回應頭。您可以使用以下代碼觀察 http.SetCookie 的結果:
fmt.Println(w.Header()["Set-Cookie"])
當前請求中不存在命名 cookie,因為 http.SetCookie 不會修改當前請求。
cookie 值的流程是這樣的:
- 服務器使用 Set-Cookie 標頭在回應中設定 cookie。
- 客戶端將 cookie 存盤在“cookie jar”中。
- 客戶端使用 Cookie 請求標頭將 jar 中的匹配 cookie 添加到請求中。
- 服務器從請求頭中獲取 cookie。
試試這個代碼。在瀏覽器中加載頁面并重繪 以觀察 cookie 值的流動。
const cookieName = "example"
cookieValue := strconv.FormatInt(time.Now().UnixNano(), 10)
fmt.Printf("Set cookie %s=%s\n", cookieName, cookieValue)
cookie := http.Cookie{Name: cookieName, Value: cookieValue, Path: "/"}
http.SetCookie(w, &cookie)
c, err := r.Cookie(cookieName)
if err != nil {
fmt.Printf("Get cookie %s error: %v\n", cookieName, err)
} else {
fmt.Printf("Get cookie %s=%s\n", cookieName, c.Value)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/353830.html
上一篇:在嵌套golang結構中使用指標
下一篇:Mongodb按內部元素分組
