Created
August 12, 2020 16:09
-
-
Save ErezYalon/5f9ca102cc3f9a5c585e90ba1f295bb5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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