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 }