Add func read and write to JSON
This commit is contained in:
64
go-demo-4/account/vault.go
Normal file
64
go-demo-4/account/vault.go
Normal 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
|
||||
}
|
||||
Reference in New Issue
Block a user