Add func read and write to JSON

This commit is contained in:
Archie Fox
2025-03-08 21:18:39 +03:00
parent 26e125577d
commit f45e200c6e
6 changed files with 120 additions and 27 deletions

View File

@@ -0,0 +1,64 @@
package account
import (
"encoding/json"
"password/files"
"strings"
"time"
"github.com/fatih/color"
)
type Vault struct {
Accounts []Account `json:"accounts"`
UpdatedAt time.Time `json:"updatedAt"`
}
func NewVault() *Vault {
file, err := files.FileRead("data.json")
if err != nil {
return &Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
}
}
var vault Vault
err = json.Unmarshal(file, &vault)
if err != nil {
color.Red("Не удалось разобрать файл data.json")
return &Vault{
Accounts: []Account{},
UpdatedAt: time.Now(),
}
}
return &vault
}
func (vault *Vault) AddAccount(acc Account) {
vault.Accounts = append(vault.Accounts, acc)
vault.UpdatedAt = time.Now()
data, err := vault.ToBytes()
if err != nil {
color.Red("Не удалось преобразовать")
}
files.FileWrite(data, "data.json")
}
func (vault *Vault) ToBytes() ([]byte, error) {
file, err := json.Marshal(vault)
if err != nil {
return nil, err
}
return file, nil
}
func (vault *Vault) FindAccountsByUrl(url string) []Account {
var accounts []Account
for _, account := range vault.Accounts {
isMatched := strings.Contains(account.Url, url)
if isMatched {
accounts = append(accounts, account)
}
}
return accounts
}