forked from demo-apps/go-gin-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.article.go
45 lines (36 loc) · 1.15 KB
/
models.article.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
// models.article.go
package main
import "errors"
type article struct {
ID int `json:"id"`
Title string `json:"title"`
Content string `json:"content"`
}
// For this demo, we're storing the article list in memory
// In a real application, this list will most likely be fetched
// from a database or from static files
var articleList = []article{
article{ID: 1, Title: "Article 1", Content: "Article 1 body"},
article{ID: 2, Title: "Article 2", Content: "Article 2 body"},
}
// Return a list of all the articles
func getAllArticles() []article {
return articleList
}
// Fetch an article based on the ID supplied
func getArticleByID(id int) (*article, error) {
for _, a := range articleList {
if a.ID == id {
return &a, nil
}
}
return nil, errors.New("Article not found")
}
// Create a new article with the title and content provided
func createNewArticle(title, content string) (*article, error) {
// Set the ID of a new article to one more than the number of articles
a := article{ID: len(articleList) + 1, Title: title, Content: content}
// Add the article to the list of articles
articleList = append(articleList, a)
return &a, nil
}