Skip to content

Instantly share code, notes, and snippets.

@ErezYalon
Created August 12, 2020 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErezYalon/5f9ca102cc3f9a5c585e90ba1f295bb5 to your computer and use it in GitHub Desktop.
Save ErezYalon/5f9ca102cc3f9a5c585e90ba1f295bb5 to your computer and use it in GitHub Desktop.
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