(file string, object interface{})
| 9 | ) |
| 10 | |
| 11 | func ReadComFile(file string, object interface{}) error { |
| 12 | functionName := "ReadComFile" |
| 13 | |
| 14 | // Initialize variables |
| 15 | var byteResult []byte |
| 16 | var readRetries int = 0 |
| 17 | var parseRetries int = 0 |
| 18 | |
| 19 | // Attempt to read file |
| 20 | for readRetries <= 10 { |
| 21 | var readErr error |
| 22 | |
| 23 | byteResult, readErr = os.ReadFile(file) |
| 24 | if readErr != nil { |
| 25 | readRetries += 1 |
| 26 | } else { |
| 27 | break |
| 28 | } |
| 29 | |
| 30 | // Introduce random delay until next try (between 50 and 100 ms) |
| 31 | time.Sleep(time.Duration(rand.Intn(100-50)+50) * time.Millisecond) |
| 32 | } |
| 33 | |
| 34 | // If read retries hit 11 |
| 35 | if readRetries == 11 { |
| 36 | // Init new ComDB |
| 37 | if newErr := InitComFile(file, &object); newErr != nil { |
| 38 | return fmt.Errorf("initializing %v failed -> %v: %w", file, functionName, newErr) |
| 39 | } |
| 40 | |
| 41 | return nil |
| 42 | } |
| 43 | |
| 44 | // Attempt to parse ComDB |
| 45 | for parseRetries <= 10 { |
| 46 | parseErr := json.Unmarshal(byteResult, &object) |
| 47 | if parseErr != nil { // If parsing fails and file is empty -> New comDB needs to initialized |
| 48 | // Increment retries |
| 49 | parseRetries += 1 |
| 50 | } else { |
| 51 | break |
| 52 | } |
| 53 | |
| 54 | // Introduce random delay until next try (between 50 and 100 ms) |
| 55 | time.Sleep(time.Duration(rand.Intn(100-50)+50) * time.Millisecond) |
| 56 | } |
| 57 | |
| 58 | // If parse retries hit 11 |
| 59 | if parseRetries == 11 { |
| 60 | // Get file info |
| 61 | statFile, statErr := os.Stat(file) |
| 62 | if statErr != nil { |
| 63 | return fmt.Errorf("could not get file information -> %v: %w", functionName, statErr) |
| 64 | } |
| 65 | |
| 66 | // If file is empty -> Init new comDB |
| 67 | if statFile.Size() == 0 { |
| 68 | // Init new ComDB |
no test coverage detected