diff options
author | Emile <hanemile@protonmail.com> | 2020-01-29 20:12:33 +0100 |
---|---|---|
committer | Emile <hanemile@protonmail.com> | 2020-01-29 20:12:33 +0100 |
commit | 7847a4e3c9ac3a431e101965de26d9f2462d36c7 (patch) | |
tree | f63accf3485f355590c51ecd34b1510a26f0669f | |
parent | e0f032a7f54dafa5a47deb9c374856551bb48280 (diff) |
load and store the state
-rw-r--r-- | src/state.go | 62 |
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 +} |