go语言中的cookie处理

本例子主要是演示go语言中关于cookie处理的几个函数,也可以在这里下载

有几点需要注意的,先提前列出来:

  1. 往客户端写入cookie,需要往respose里写,而不是request,这个很容易混淆,因为request有AddCookie方法,这个看起来就很吸引人使用。而往response的方法是http包里的函数SetCookie 。实际上,request的AddCookie是把http当做客户端的时候使用的。

  2. 写cookie需要在往response里写入body前进行。特别要注意这个时机问题。

  3. 删除cookie通过设置cookie的MaxAge为负数来实现。

全部代码如下(请从这里取得最新代码)

测试的话请运行此程序然后在浏览器确认。

package main

import (
    "io"
    "net/http"
    "log"
    "fmt"
    "time"
)

func DrawMenu(w http.ResponseWriter){
    w.Header().Set("Content-Type", "text/html")
    io.WriteString(w, "<a href='/'>HOME <ba><br/>" + "\n")
    io.WriteString(w, "<a href='/readcookie'>Read Cookie <ba><br/>" + "\n")
    io.WriteString(w, "<a href='/writecookie'>Write Cookie <ba><br/>" + "\n")
    io.WriteString(w, "<a href='/deletecookie'>Delete Cookie <ba><br/>" + "\n")

}

func IndexServer(w http.ResponseWriter, req *http.Request) {
    // draw menu
    DrawMenu(w)
}


func ReadCookieServer(w http.ResponseWriter, req *http.Request) {

    // draw menu
    DrawMenu(w)

    // read cookie
    var cookie,err = req.Cookie("testcookiename")
    if err == nil {
        var cookievalue = cookie.Value
        io.WriteString(w, "<b>get cookie value is " + cookievalue + "</b>\n")
    }

}

func WriteCookieServer(w http.ResponseWriter, req *http.Request) {
    // set cookies.
    expire := time.Now().AddDate(0, 0, 1)
    cookie := http.Cookie{Name: "testcookiename", Value: "testcookievalue", Path: "/", Expires: expire, MaxAge: 86400}

    http.SetCookie(w, &cookie)

    // 
    // we can not set cookie after writing something to ResponseWriter
    // if so ,we cannot set cookie succefully.
    // 
    // so we have draw menu after set cookie
    DrawMenu(w)

}


func DeleteCookieServer(w http.ResponseWriter, req *http.Request) {

    // set cookies.
    cookie := http.Cookie{Name: "testcookiename", Path: "/", MaxAge: -1}
    http.SetCookie(w, &cookie)

    // ABOUT MaxAge
    // MaxAge=0 means no 'Max-Age' attribute specified.
    // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
    // MaxAge>0 means Max-Age attribute present and given in seconds

    // draw menu
    DrawMenu(w)

}

func main() {

    http.HandleFunc("/", IndexServer)
    http.HandleFunc("/readcookie", ReadCookieServer)
    http.HandleFunc("/writecookie", WriteCookieServer)
    http.HandleFunc("/deletecookie", DeleteCookieServer)

    fmt.Println("listen on 3000")
    err := http.ListenAndServe(":3000", nil)

    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}


Posted in go, Tech

无觅相关文章插件,快速提升流量