@@ -27,6 +27,7 @@ import (
2727 "net"
2828 "net/http"
2929 "os"
30+ "path/filepath"
3031 "strconv"
3132 "sync"
3233 "sync/atomic"
@@ -41,27 +42,27 @@ var (
4142 fileMutex sync.Mutex
4243)
4344
44- const fileCounterPath = "/home/counter/a.txt"
45-
46- func incrementFileCounter () int {
45+ func incrementFileCounter (filePath string ) int {
4746 fileMutex .Lock ()
4847 defer fileMutex .Unlock ()
4948 counter := 0
50- data , err := os .ReadFile (fileCounterPath )
49+ data , err := os .ReadFile (filePath )
5150 if err == nil {
5251 if i , err := strconv .Atoi (string (data )); err == nil {
5352 counter = i
5453 }
5554 }
5655 counter ++
57- err = os .WriteFile (fileCounterPath , []byte (strconv .Itoa (counter )), 0o644 )
56+ err = os .WriteFile (filePath , []byte (strconv .Itoa (counter )), 0o644 )
5857 if err != nil {
5958 return - 1
6059 }
6160 return counter
6261}
6362
6463func main () {
64+ fileCounterDirectory := pflag .String ("file-counter-directory" , "/home/counter" , "Directory for file counter" )
65+ validateExistingFilePath := pflag .String ("validate-existing-file-path" , "" , "Path to existing file to validate reading" )
6566 pflag .Parse ()
6667 ctx := context .Background ()
6768
@@ -70,11 +71,23 @@ func main() {
7071 defaultMux := http .NewServeMux ()
7172 defaultMux .HandleFunc ("/" , func (w http.ResponseWriter , r * http.Request ) {
7273 ctx := r .Context ()
73- fileCounter := incrementFileCounter ()
74-
74+ fileCounter := incrementFileCounter (filepath .Join (* fileCounterDirectory , "a.txt" ))
7575 memoryCounter := atomic .AddUint64 (& requestCount , 1 )
7676 currentIP := getCurrentIP ()
77- response := fmt .Sprintf ("hello from: %s | preserved memory count: %d | preserved file counter: %d\n " , currentIP , memoryCounter , fileCounter )
77+
78+ fileContentStr := ""
79+ if * validateExistingFilePath != "" {
80+ fileContent , err := os .ReadFile (* validateExistingFilePath )
81+ if err != nil {
82+ fileResponse := fmt .Sprintf ("failed to read test file: %s\n " , err .Error ())
83+ w .WriteHeader (http .StatusOK )
84+ w .Write ([]byte (fileResponse ))
85+ return
86+ }
87+ fileContentStr = fmt .Sprintf (" | file content: %s" , string (fileContent ))
88+ }
89+
90+ response := fmt .Sprintf ("hello from: %s | preserved memory count: %d | preserved file counter: %d%s\n " , currentIP , memoryCounter , fileCounter , fileContentStr )
7891 slog .InfoContext (ctx , "Handled request" , slog .String ("response" , response ))
7992
8093 w .WriteHeader (http .StatusOK )
0 commit comments