### Cookies
Cookie 是用戶在訪問網站時服務器發送過來存儲在瀏覽器上的一小段數據。每次用戶訪問網頁,瀏覽器都把 Cookies 發送回服務器以提醒服務器這個用戶以前干過什么。 Cookie 用來提供一個可靠的途徑讓服務器記住一些狀態信息(比如在線商城中添加物品到購物車)或者記錄用戶的瀏覽器行為(比如點擊了某個按鈕,登錄,哪個頁面被訪問過)。 Cookie 也可以用來存儲用戶輸入過的表單內容像電話號碼,地址等等。
Cookie 屬性
| 屬性 | 可選 |
| --- | --- |
| Name | No |
| Value | No |
| Path | Yes |
| Domain | Yes |
| Expires |Yes |
| Secure | Yes |
| HTTPOnly | Yes |
創建一個 Cookie:
~~~
func SimpleCookie(ctx dotweb.Context) error {
ctx.SetCookieValue("test", "val", 1000)
return nil
}
func WriteCookie(ctx dotweb.Context) error {
cookie := &http.Cookie{Name: "test",
Value: url.QueryEscape("val"),
MaxAge: 1000,
HttpOnly: true}
ctx.SetCookie(cookie)
return nil
}
~~~
讀取 Cookie:
~~~
func ReadCookie(ctx dotweb.Context) error {
cookie, err:=ctx.ReadCookie("test")
if err != nil {
return err
}
fmt.Println(cookie.Name)
fmt.Println(cookie.Value)
ctx.WriteString("read a cookie")
return nil
}
~~~