Created
August 12, 2020 16:09
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" | |
const VISITS_COUNTER_FILE = "/tmp/visits-counter" | |
func updateVisitsCounter () uint64 { | |
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