From 7847a4e3c9ac3a431e101965de26d9f2462d36c7 Mon Sep 17 00:00:00 2001 From: Emile Date: Wed, 29 Jan 2020 20:12:33 +0100 Subject: load and store the state --- src/state.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/state.go (limited to 'src/state.go') 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 +} -- cgit 1.4.1