-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.go
201 lines (179 loc) · 5.45 KB
/
app.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
// cidre sample: simple wiki app
package main
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/mattn/go-sqlite3"
"github.com/yuin/cidre"
"html/template"
"net/http"
"path/filepath"
"strings"
"time"
)
type WikiConfig struct {
SiteName string
SiteDescription string
DataDirectory string
}
var wikiConfig = &WikiConfig{
SiteName: "cidre Wiki",
SiteDescription: "Simple wiki app written in cidre",
DataDirectory: "./data",
}
type View struct {
Context *cidre.Context
App *cidre.App
Config *WikiConfig
Title string
Data interface{}
Flashes map[string][]string
}
func NewView(w http.ResponseWriter, r *http.Request, title string, data interface{}) *View {
ctx := cidre.RequestContext(r)
self := &View{ctx, ctx.App, wikiConfig, title, data, ctx.Session.Flashes()}
return self
}
type Article struct {
Id int
Name string
Body string
UpdatedAt time.Time
CreatedAt time.Time
}
// gorm.DB is thread safe
var DB gorm.DB
func InitDB(dataFilePath string) error {
var err error
DB, err = gorm.Open("sqlite3", dataFilePath)
if err != nil {
return err
}
if !DB.HasTable(Article{}) {
DB.CreateTable(Article{})
articleModel := DB.Model(Article{})
articleModel.AddIndex("articles_name_idx", "name")
articleModel.AddIndex("articles_updated_at_idx", "updated_at")
}
return nil
}
func FindArticle(db *gorm.DB, name string) (*Article, error) {
var article Article
err := db.Where("name = ?", name).First(&article).Error
return &article, err
}
func FindArticles(db *gorm.DB) []Article {
articles := make([]Article, 0, 10)
db.Order("updated_at desc").Find(&articles)
return articles
}
func DBTransactionMiddleware(w http.ResponseWriter, r *http.Request) {
ctx := cidre.RequestContext(r)
ctx.Set("db", DB.Begin())
defer func() {
status := w.(cidre.ResponseWriter).Status()
if status >= 200 && status < 400 {
ctx.Get("db").(*gorm.DB).Commit()
} else {
ctx.Get("db").(*gorm.DB).Rollback()
}
}()
ctx.MiddlewareChain.DoNext(w, r)
}
func ctxdb(r *http.Request) (*cidre.Context, *gorm.DB) {
ctx := cidre.RequestContext(r)
db := ctx.Get("db").(*gorm.DB)
return ctx, db
}
func main() {
// Load configurations
appConfig := cidre.DefaultAppConfig()
sessionConfig := cidre.DefaultSessionConfig()
_, err := cidre.ParseIniFile("app.ini",
// cidre
cidre.ConfigMapping{"cidre", appConfig},
// session middleware
cidre.ConfigMapping{"session.base", sessionConfig},
// this app
cidre.ConfigMapping{"wiki", wikiConfig},
)
if err != nil {
panic(err)
}
app := cidre.NewApp(appConfig)
// Set template function on setup
app.Hooks.Add("setup", func(w http.ResponseWriter, r *http.Request, data interface{}) {
config := app.Renderer.(*cidre.HtmlTemplateRenderer).Config
config.FuncMap["nl2br"] = func(text string) template.HTML {
return template.HTML(strings.Replace(text, "\n", "<br />", -1))
}
})
// Auto transaction management
app.Use(DBTransactionMiddleware)
// Use the session middleware for flash messaging
app.Use(cidre.NewSessionMiddleware(app, sessionConfig, nil))
root := app.MountPoint("/")
// serve static files
root.Static("statics", "statics", "./statics")
root.Get("show_pages", "", func(w http.ResponseWriter, r *http.Request) {
_, db := ctxdb(r)
app.Renderer.Html(w, "show_pages", NewView(w, r, "List pages", FindArticles(db)))
})
root.Get("show_page", "pages/(?P<name>[^/]+)", func(w http.ResponseWriter, r *http.Request) {
ctx, db := ctxdb(r)
name := ctx.PathParams.Get("name")
article, err := FindArticle(db, name)
if err != nil {
switch err {
case gorm.RecordNotFound:
app.OnNotFound(w, r)
default:
app.OnPanic(w, r, err)
}
return
}
app.Renderer.Html(w, "show_page", NewView(w, r, "Page:"+name, article))
})
root.Get("edit_page", "pages/(?P<name>[^/]+)/edit", func(w http.ResponseWriter, r *http.Request) {
ctx, db := ctxdb(r)
name := ctx.PathParams.Get("name")
article, _ := FindArticle(db, name)
article.Name = name
app.Renderer.Html(w, "edit_page", NewView(w, r, "EDIT: "+name, article))
})
root.Post("save_page", "pages/(?P<name>[^/]+)", func(w http.ResponseWriter, r *http.Request) {
ctx, db := ctxdb(r)
name := ctx.PathParams.Get("name")
article, _ := FindArticle(db, name)
article.Name = name
article.Body = r.FormValue("body")
if db.Save(article).Error != nil {
ctx.Session.AddFlash("error", "Failed to save a page: "+err.Error())
http.Redirect(w, r, app.BuildUrl("edit_page", name), http.StatusFound)
} else {
ctx.Session.AddFlash("info", "Page updated")
http.Redirect(w, r, app.BuildUrl("show_page", name), http.StatusFound)
}
})
root.Delete("delete_page", "pages/(?P<name>[^/]+)", func(w http.ResponseWriter, r *http.Request) {
ctx, db := ctxdb(r)
name := ctx.PathParams.Get("name")
article, err := FindArticle(db, name)
if err != nil && db.Delete(article).Error == nil {
ctx.Session.AddFlash("info", "Page deleted")
http.Redirect(w, r, app.BuildUrl("show_pages"), http.StatusFound)
} else {
ctx.Session.AddFlash("error", "Failed to delete a page: "+err.Error())
http.Redirect(w, r, app.BuildUrl("edit_page", name), http.StatusFound)
}
})
app.Hooks.Add("start_request", func(w http.ResponseWriter, r *http.Request, data interface{}) {
w.Header().Add("X-Server", "Go")
})
app.OnNotFound = func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "Oops! Page not found.")
}
InitDB(filepath.Join(wikiConfig.DataDirectory, "wiki.bin"))
app.Run()
}