This repository has been archived by the owner on Jul 6, 2021. It is now read-only.
/
todoapp.go
274 lines (234 loc) · 7.07 KB
/
todoapp.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package main
import (
"errors"
"fmt"
todo "github.com/JamesClonk/go-todotxt"
"github.com/codegangsta/cli"
"github.com/codegangsta/martini"
"github.com/codegangsta/martini-contrib/binding"
"github.com/codegangsta/martini-contrib/render"
"log"
"net/http"
"os"
"strconv"
"time"
)
var (
logFlags = log.Ldate | log.Ltime
logPrefix = "[todoapp] "
configFile = "todoapp.config"
port = "4004"
)
type View struct {
Title string
}
func main() {
app := cli.NewApp()
app.Name = "todoapp"
app.Usage = "A browser-based Todo.txt application"
app.Version = "1.0.0"
app.Author = "JamesClonk"
app.Email = "jamesclonk@jamesclonk.ch"
app.Action = mainAction
app.Flags = []cli.Flag{
cli.IntFlag{"port,p", 4004, "port for the todoapp web server"},
cli.StringFlag{"file,f", "todo.txt", "filename/path of todo.txt file to use"},
cli.StringFlag{"config,c", "todoapp.config", "filename/path of configuration file to use"},
}
app.Run(os.Args)
}
func mainAction(c *cli.Context) {
parseOptions(c)
m := setupMartini()
log.SetFlags(0)
log.SetPrefix(logPrefix)
log.Println("")
log.Println("------------------------------------------------------------------")
log.Println("")
log.Println(" Welcome to 'todoapp', a browser-based Todo.txt application")
log.Printf(" Start your browser and point it to http://localhost:%v/\n", port)
log.Println("")
log.Println("------------------------------------------------------------------")
log.Println("")
log.SetFlags(logFlags)
log.SetPrefix(logPrefix)
log.Printf("todoapp started and listening on port %v\n", port)
http.ListenAndServe(":"+port, m)
}
func parseOptions(c *cli.Context) {
port = strconv.Itoa(c.Int("port"))
if c.IsSet("config") {
configFile = c.String("config")
}
config, err := readConfigurationFile(configFile)
if err != nil {
log.Fatalf("Could not read configuration file: %v", err)
return
}
if c.IsSet("file") {
// overwrite configuration file setting for todo.txt file, if given as commandline parameter
config.TodoTxtFilename = c.String("file")
if err := config.writeConfigurationFile(configFile); err != nil {
log.Fatalf("Could not update configuration file: %v", err)
}
}
// check if file actually exists, otherwise create new file
if err := checkAndCreateFile(config.TodoTxtFilename); err != nil {
log.Fatal(err)
}
}
func setupMartini() *martini.Martini {
r := martini.NewRouter()
m := martini.New()
m.Use(martini.Recovery())
m.Use(martini.Static("assets", martini.StaticOptions{SkipLogging: true})) // skip logging on static content
m.Use(martini.Logger())
m.Use(render.Renderer(render.Options{
Directory: "templates",
Layout: "layout",
Extensions: []string{".html"},
Delims: render.Delims{"{[{", "}]}"},
IndentJSON: true,
}))
m.Use(ConfigOptions(configFile))
m.Use(TaskList())
m.Map(log.New(os.Stdout, logPrefix, logFlags))
m.Action(r.Handle)
setupRoutes(r)
return m
}
func setupRoutes(r martini.Router) {
// static
r.Get("/", func(r render.Render) {
r.HTML(http.StatusOK, "index", View{Title: "A browser-based Todo.txt application"})
})
r.NotFound(func(r render.Render) {
r.HTML(http.StatusNotFound, "404", View{Title: "404 - Not Found"})
})
// api - for tasks
r.Get("/api/tasks", func(tasks todo.TaskList, r render.Render) {
r.JSON(http.StatusOK, tasks)
})
r.Get("/api/task/:id", func(tasks todo.TaskList, params martini.Params, r render.Render) {
id, err := strconv.Atoi(params["id"])
if err != nil {
r.Error(http.StatusInternalServerError)
return
}
task, err := tasks.GetTask(id)
if err != nil {
r.Error(http.StatusNotFound)
return
}
r.JSON(http.StatusOK, task)
})
r.Post("/api/task", binding.Bind(todo.Task{}), func(newTask todo.Task, tasks todo.TaskList, config *Config, params martini.Params, r render.Render) {
newTask.CreatedDate = time.Now()
tasks.AddTask(&newTask)
if err := tasks.WriteToFilename(config.TodoTxtFilename); err != nil {
r.Error(http.StatusInternalServerError)
return
}
r.JSON(http.StatusCreated, newTask)
})
r.Put("/api/task/:id", binding.Bind(todo.Task{}), func(updatedTask todo.Task, tasks todo.TaskList, config *Config, params martini.Params, r render.Render) {
id, err := strconv.Atoi(params["id"])
if err != nil {
r.Error(http.StatusInternalServerError)
return
}
currentTask, err := tasks.GetTask(id)
if err != nil {
r.Error(http.StatusNotFound)
return
}
*currentTask = updatedTask
if err := tasks.WriteToFilename(config.TodoTxtFilename); err != nil {
r.Error(http.StatusInternalServerError)
return
}
r.JSON(http.StatusOK, updatedTask)
})
r.Delete("/api/task/:id", func(tasks todo.TaskList, config *Config, params martini.Params, r render.Render) {
id, err := strconv.Atoi(params["id"])
if err != nil {
r.Error(http.StatusInternalServerError)
return
}
if err := tasks.RemoveTaskById(id); err != nil {
r.Error(http.StatusNotFound)
return
}
if err := tasks.WriteToFilename(config.TodoTxtFilename); err != nil {
r.Error(http.StatusInternalServerError)
return
}
r.JSON(http.StatusNoContent, `{}`)
})
r.Delete("/api/tasks", func(tasks todo.TaskList, config *Config, r render.Render) {
openTasks := make(todo.TaskList, 0)
for _, task := range tasks {
if !task.Completed {
openTasks.AddTask(&task)
}
}
if err := openTasks.WriteToFilename(config.TodoTxtFilename); err != nil {
r.Error(http.StatusInternalServerError)
return
}
r.JSON(http.StatusOK, openTasks)
})
// api - for config file
r.Get("/api/config", func(config *Config, r render.Render) {
r.JSON(http.StatusOK, config)
})
r.Put("/api/config", binding.Bind(Config{}), func(bindConfig Config, r render.Render) {
if err := bindConfig.writeConfigurationFile(configFile); err != nil {
r.Error(http.StatusInternalServerError)
return
}
r.JSON(http.StatusOK, bindConfig)
})
}
func checkAndCreateFile(filename string) error {
// check if file exists, otherwise create new file
if _, err := os.Stat(filename); os.IsNotExist(err) {
file, err := os.Create(filename)
if err != nil {
return errors.New(fmt.Sprintf("%s could not be created: %v", filename, err))
}
file.Close()
}
return nil
}
// Add todotxt.TaskList to martini context
func TaskList() martini.Handler {
return func(c martini.Context, r render.Render, config *Config) {
if err := checkAndCreateFile(config.TodoTxtFilename); err != nil {
r.HTML(http.StatusInternalServerError, "500", err)
return
}
tasks, err := todo.LoadFromFilename(config.TodoTxtFilename)
if err != nil {
r.HTML(http.StatusInternalServerError, "500", err)
return
}
c.Map(tasks)
c.Next()
}
}
// Add configuration options to martini context
func ConfigOptions(filename string) martini.Handler {
return func(c martini.Context, r render.Render) {
config, err := readConfigurationFile(filename)
if err != nil {
r.HTML(http.StatusInternalServerError, "500", err)
return
}
c.Map(config)
c.Next()
}
}