Add func read and write to JSON
This commit is contained in:
@@ -1,14 +1,12 @@
|
||||
package account
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/fatih/color"
|
||||
"math/rand/v2"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/fatih/color"
|
||||
)
|
||||
|
||||
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGIJKLMNOPQRSTUVWXYZ1234567890-*!?()#$%&")
|
||||
@@ -22,17 +20,9 @@ type Account struct {
|
||||
}
|
||||
|
||||
// метод вывода пароля
|
||||
func (acc *Account) OutputPassword() {
|
||||
func (acc *Account) Output() {
|
||||
c := color.New(color.FgRed, color.Italic, color.Bold)
|
||||
c.Printf("password: %v\n", acc.Password)
|
||||
}
|
||||
|
||||
func (acc *Account) ToBytes() ([]byte, error) {
|
||||
file, err := json.Marshal(acc)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return file, nil
|
||||
c.Printf("password: %v, login: %v, URL: %v\n", acc.Password, acc.Login, acc.Url)
|
||||
}
|
||||
|
||||
// метод генерации пароля
|
||||
|
||||
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