Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import "net/http"
import "fmt"
import "log"
import "io/ioutil"
import "strconv"
import "sync"
const VISITS_COUNTER_FILE = "/tmp/visits-counter"
var mutex = sync.Mutex{}
func updateVisitsCounter () uint64 {
mutex.Lock()
defer mutex.Unlock()
curCounter, err := ioutil.ReadFile(VISITS_COUNTER_FILE)
if err != nil {
// @todo error handling
}
// convert current value to uint64
updatedCounter, err := strconv.ParseUint(string(curCounter), 10, 64)
if err != nil {
// @todo error handling
}
updatedCounter = updatedCounter + 1;
// write updatedCounter to file
err = ioutil.WriteFile(VISITS_COUNTER_FILE, []byte(strconv.FormatUint(updatedCounter, 10)), 0640)
if err != nil {
// @todo error handling
}
return updatedCounter
}
func main () {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var counter uint64 = updateVisitsCounter()
fmt.Fprintf(w, "Hello, you're visitor #%d", counter)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment