Returns false if file does not exist. cmn.Panics if file is corrupt.
(filePath string)
| 44 | // Returns false if file does not exist. |
| 45 | // cmn.Panics if file is corrupt. |
| 46 | func (a *addrBook) loadFromFile(filePath string) bool { |
| 47 | // If doesn't exist, do nothing. |
| 48 | _, err := os.Stat(filePath) |
| 49 | if os.IsNotExist(err) { |
| 50 | return false |
| 51 | } |
| 52 | |
| 53 | // Load addrBookJSON{} |
| 54 | r, err := os.Open(filePath) |
| 55 | if err != nil { |
| 56 | panic(fmt.Sprintf("Error opening file %s: %v", filePath, err)) |
| 57 | } |
| 58 | defer r.Close() |
| 59 | aJSON := &addrBookJSON{} |
| 60 | dec := json.NewDecoder(r) |
| 61 | err = dec.Decode(aJSON) |
| 62 | if err != nil { |
| 63 | panic(fmt.Sprintf("Error reading file %s: %v", filePath, err)) |
| 64 | } |
| 65 | |
| 66 | // Restore all the fields... |
| 67 | // Restore the key |
| 68 | a.key = aJSON.Key |
| 69 | // Restore .bucketsNew & .bucketsOld |
| 70 | for _, ka := range aJSON.Addrs { |
| 71 | for _, bucketIndex := range ka.Buckets { |
| 72 | bucket := a.getBucket(ka.BucketType, bucketIndex) |
| 73 | bucket[ka.Addr.String()] = ka |
| 74 | } |
| 75 | a.addrLookup[ka.ID()] = ka |
| 76 | if ka.BucketType == bucketTypeNew { |
| 77 | a.nNew++ |
| 78 | } else { |
| 79 | a.nOld++ |
| 80 | } |
| 81 | } |
| 82 | return true |
| 83 | } |