about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/state.go62
1 files changed, 62 insertions, 0 deletions
diff --git a/src/state.go b/src/state.go
new file mode 100644
index 0000000..0f62a5b
--- /dev/null
+++ b/src/state.go
@@ -0,0 +1,62 @@
+package main
+
+import (
+	"fmt"
+	"io/ioutil"
+	"log"
+	"os"
+	"strconv"
+)
+
+// loadState loads the state from the config file
+func loadState(config config) error {
+	stateFilePath := config.stateFile
+
+	// try to read the statefile
+	buf, err := os.Open(stateFilePath)
+	if err != nil {
+		return fmt.Errorf("Could not read the/a stateFile: %s", err)
+	}
+
+	defer buf.Close()
+
+	// Read the files content
+	content, err := ioutil.ReadAll(buf)
+	if err != nil {
+		return fmt.Errorf("Could not read the stateFiles content: %s", err)
+	}
+
+	// Apply the state by setting the metricsNumPasswords value accordingly
+	// This parses the statefile (which is supposed to only contain one line).
+	// The newline is stripped manually.
+	metricsNumPasswords, err = strconv.Atoi(string(content)[:len(content)-1])
+	if err != nil {
+		return fmt.Errorf("Could not parse the statefiles content: %s", err)
+	}
+
+	// If all went well, return no error
+	log.Printf("Statefile successfully loaded")
+	return nil
+}
+
+// WriteStateToFile writse the state (amount of hits) to a file
+func WriteStateToFile(config config) error {
+	stateFilePath := config.stateFile
+
+	// create the statefile
+	buf, err := os.Create(stateFilePath)
+	if err != nil {
+		return fmt.Errorf("could not create a statefile at %s: %s", stateFilePath, err)
+	}
+	defer buf.Close()
+
+	// write the state to the file
+	_, err = buf.WriteString(string(fmt.Sprintf("%d", metricsNumPasswords)))
+	if err != nil {
+		return fmt.Errorf("could not write the state to %s, %s", stateFilePath, err)
+	}
+
+	// If all went well, return no error
+	log.Printf("Statefile successfully written to %s", stateFilePath)
+	return nil
+}