1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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
}
|