Files
purpleschool/go-demo-4/account/vault.go
2025-03-09 11:39:45 +03:00

85 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.save()
}
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
}
func (vault *Vault) DeleteAccountByUrl(url string) bool {
var accounts []Account
isDeleted := false
for _, account := range vault.Accounts {
isMatched := strings.Contains(account.Url, url)
if !isMatched {
accounts = append(accounts, account)
continue
}
isDeleted = true
}
vault.Accounts = accounts
vault.save()
return isDeleted
}
func (vault *Vault) save() {
vault.UpdatedAt = time.Now()
data, err := vault.ToBytes()
if err != nil {
color.Red("Не удалось преобразовать")
}
files.FileWrite(data, "data.json")
}