/
account.go
112 lines (98 loc) · 2.03 KB
/
account.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package model
import (
"errors"
"fmt"
uuid "github.com/gofrs/uuid"
)
// Account example
type Account struct {
ID int `json:"id" example:"1" format:"int64"`
Name string `json:"name" example:"account name"`
UUID uuid.UUID `json:"uuid" example:"550e8400-e29b-41d4-a716-446655440000" format:"uuid"`
}
// example
var (
ErrNameInvalid = errors.New("name is empty")
)
// AddAccount example
type AddAccount struct {
Name string `json:"name" example:"account name"`
}
// Validation example
func (a AddAccount) Validation() error {
switch {
case len(a.Name) == 0:
return ErrNameInvalid
default:
return nil
}
}
// UpdateAccount example
type UpdateAccount struct {
Name string `json:"name" example:"account name"`
}
// Validation example
func (a UpdateAccount) Validation() error {
switch {
case len(a.Name) == 0:
return ErrNameInvalid
default:
return nil
}
}
// AccountsAll example
func AccountsAll(q string) ([]Account, error) {
if q == "" {
return accounts, nil
}
as := []Account{}
for k, v := range accounts {
if q == v.Name {
as = append(as, accounts[k])
}
}
return as, nil
}
// AccountOne example
func AccountOne(id int) (Account, error) {
for _, v := range accounts {
if id == v.ID {
return v, nil
}
}
return Account{}, ErrNoRow
}
// Insert example
func (a Account) Insert() (int, error) {
accountMaxID++
a.ID = accountMaxID
a.Name = fmt.Sprintf("account_%d", accountMaxID)
accounts = append(accounts, a)
return accountMaxID, nil
}
// Delete example
func Delete(id int) error {
for k, v := range accounts {
if id == v.ID {
accounts = append(accounts[:k], accounts[k+1:]...)
return nil
}
}
return fmt.Errorf("account id=%d is not found", id)
}
// Update example
func (a Account) Update() error {
for k, v := range accounts {
if a.ID == v.ID {
accounts[k].Name = a.Name
return nil
}
}
return fmt.Errorf("account id=%d is not found", a.ID)
}
var accountMaxID = 3
var accounts = []Account{
{ID: 1, Name: "account_1"},
{ID: 2, Name: "account_2"},
{ID: 3, Name: "account_3"},
}