Web状态,对于我们从c/c++转过来的人来说还是很重视的啊
但,如何用好cookie来让我心顺畅,目前还是有点障碍
可能是我没能完全理解cookie
但是,如果由浏览器客户端决定自己绑定那个cookie;啥时候取消绑定;对于我来说就愉快多了。
请看
package main
import (
"fmt"
"net/http"
)
func SayHello(w http.ResponseWriter, req *http.Request) {
w.Write([] byte("Hello World!"))
}
func ReadCookieServer(w http.ResponseWriter, req *http.Request) {
cookie, err := req.Cookie("zcl_cookie")
if (err==nil) {
cookievalue := cookie.Value
w.Write([]byte("<b>cookie value is : "+cookievalue+"</b>
"))
} else {
w.Write([]byte("<b> read error: "+err.Error()+"</b>
"))
}
}
func WriteCookieServer(w http.ResponseWriter, req *http.Request) {
cookie := http.Cookie{Name:"zcl_cookie", Value:"zcl_cookie_value", Path:"/", MaxAge:100}
http.SetCookie(w, &cookie)
w.Write([]byte("<b>set cookie is succeed!</b>
"))
}
func DeleteCookieServer(w http.ResponseWriter, req *http.Request) {
cookie := http.Cookie{Name:"zcl_cookie", Path:"/", MaxAge:-1}
http.SetCookie(w, &cookie)
w.Write([]byte("<b>delete cookie is succeed!</b>
"))
}
func main() {
http.HandleFunc("/", SayHello)
http.HandleFunc("/readcookie", ReadCookieServer)
http.HandleFunc("/writecookie", WriteCookieServer)
http.HandleFunc("/deletecookie", DeleteCookieServer)
fmt.Println("server is running at 8086")
http.ListenAndServe(":8086", nil)
}
结果:
Finally:
服务器只要响应有效cookie,就可以维护客户端的历史信息了。
客户端会自己清除服务器端的cookie,服务器相应的再清除客户端历史信息
这是我的理解,我也打算这么干。
哈哈哈
不管你干不干,反正,我是干了!