Use expvar for web page analystics


 

Golang's package expvar exposes variables via HTTP.  Operations on the exposed varibles are atomic. It can be used for the purpose of web page analytics such as counting the number of visitors of a page. In the following example, the variable "count" is incremented by one when the page "/greeting" is visted. 

 

package main

import (
    "bytes"
    "expvar"
    "html/template"
    "log"
    "net/http"
)

var count expvar.Int

func greetingHandler(w http.ResponseWriter, r *http.Request) {
    count.Add(1)
    w.Write([]byte("Hello"))
}

func statHandler(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("Count:" + count.String()))
}

func main() {
    http.HandleFunc("/greeting", greetingHandler)
    http.HandleFunc("/stat", statHandler)

    log.Fatal(http.ListenAndServe(":8090", nil))
}



  


Comments:

Write a comment
Anonymous

Captcha image

Reload

Type the number you see in the image above: