Golang 网站访问计数器
List of HTTP header fields
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
注意:Google浏览器,每次请求访问Web服务器都会发送第2个请求,读取favicon.ico,这样对于统计函数count会每次多计数1次,count函数的路由因为设置成了 “/”,路由地址只要在在根目录,就会发生,所以,用户每点一次页面,计数器每次+2,而不是+1,显然这是不对的,忽略此路由地址请求:http://127.0.0.1:9090/favicon.ico 才是正确的实现方法;其它浏览器没这样的问题,提醒:根目录路由使用时要小心了,避免此坑 。。。。。。
/root/code/go/src/contoso.org/hello/main.go: package main import ( "encoding/json" "html/template" "log" "net/http" "fmt" "github.com/astaxie/beego/session" ) var globalSessions *session.Manager func init() { config := `{"cookieName":"gosessionid","gclifetime":3600,"enableSetCookie":true}` // conf := new(session.ManagerConfig) if err := json.Unmarshal([]byte(config),conf); err != nil { log.Fatal("json decode error",err) } globalSessions,_ = session.NewManager("memory",conf) go globalSessions.GC() } func main() { http.HandleFunc("/",count) //设置访问的路由 err := http.ListenAndServe(":9090",nil) //设置监听的端口 if err != nil { log.Fatal("ListenAndServe: ",err) } } //网站访问计数器 func count(w http.ResponseWriter,r *http.Request) { fmt.Println("Requesting Addr 2: ",r.URL.Path) //忽略此路由地址请求:http://127.0.0.1:9090/favicon.ico if r.URL.Path != "/favicon.ico" { sess,_ := globalSessions.SessionStart(w,r) ct := sess.Get("countnum") if ct == nil { sess.Set("countnum",1) } else { sess.Set("countnum",(ct.(int) + 1)) } t,_ := template.ParseFiles("count.gtpl") w.Header().Set("Content-Type","text/html") t.Execute(w,sess.Get("countnum")) } }
/root/code/go/src/contoso.org/hello/count.gtpl: Now count:{{.}}
有时想遍历w,r下的Header信息,红字标识的代码很有用处(打印输出所有键值对):
fmt.Println("n ****** Request Header: ******")
接下来我打算比较一下"enableSetCookie":true 与 "enableSetCookie":false 在服务器端与客户不同输出效果:
第1种情形:
第2种情形:
//网站访问计数器 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |