-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.go
More file actions
91 lines (72 loc) · 1.47 KB
/
db.go
File metadata and controls
91 lines (72 loc) · 1.47 KB
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
package main
import (
"errors"
"sync"
)
var errNotFound = errors.New("Article not found")
// Article is content posted by a user
type Article struct {
ID int `json:"id"`
User string `json:"user"`
Body string `json:"body"`
}
// DB holds our Articles
type DB struct {
sync.RWMutex
articles []Article
}
// FindOne finds an article by its ID
func (db *DB) FindOne(id int) (Article, error) {
db.RLock()
defer db.RUnlock()
for _, p := range db.articles {
if p.ID == id {
return p, nil
}
}
return Article{}, errNotFound
}
// FindAll returns all Articles
func (db *DB) FindAll() []Article {
db.RLock()
defer db.RUnlock()
return db.articles
}
// Insert adds an Article to the DB. It sets the ID field and returns the modified
// Article.
func (db *DB) Insert(p Article) Article {
db.Lock()
defer db.Unlock()
id := 0
for _, article := range db.articles {
if article.ID > id {
id = article.ID
}
}
id++
p.ID = id
db.articles = append(db.articles, p)
return p
}
// Update finds an Article in the DB by ID and replaces it
func (db *DB) Update(p Article) {
db.Lock()
defer db.Unlock()
for i, article := range db.articles {
if article.ID == p.ID {
db.articles[i] = p
return
}
}
}
// Delete removes an Article from the collection by ID
func (db *DB) Delete(id int) {
db.Lock()
defer db.Unlock()
for i, article := range db.articles {
if article.ID == id {
db.articles = append(db.articles[:i], db.articles[i+1:]...)
return
}
}
}