-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.go
56 lines (46 loc) · 1020 Bytes
/
data.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
package main
import (
"errors"
"time"
)
// 保存 Topic,没有考虑并发问题
var TopicCache = make([]*Topic, 0, 16)
type Topic struct {
Id int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
CreatedAt time.Time `json:"created_at"`
}
func FindTopic(id int) (*Topic, error) {
if err := checkIndex(id); err != nil {
return nil, err
}
return TopicCache[id-1], nil
}
func (t *Topic) Create() error {
t.Id = len(TopicCache) + 1
t.CreatedAt = time.Now()
TopicCache = append(TopicCache, t)
return nil
}
func (t *Topic) Update() error {
if err := checkIndex(t.Id); err != nil {
return err
}
TopicCache[t.Id-1] = t
return nil
}
// 简单的将对应的 slice 位置置为 nil
func (t *Topic) Delete() error {
if err := checkIndex(t.Id); err != nil {
return err
}
TopicCache[t.Id-1] = nil
return nil
}
func checkIndex(id int) error {
if id > 0 && len(TopicCache) <= id-1 {
return errors.New("The topic is not exists!")
}
return nil
}