forked from shijuvar/go-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
task.go
80 lines (72 loc) · 1.76 KB
/
task.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
package task
import (
"fmt"
"html/template"
"net/http"
"time"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
type Task struct {
Name string
Description string
CreatedOn time.Time
}
const taskForm = `
<html>
<body>
<form action="/save" method="post">
<p>Task Name: <input type="text" name="taskname" ></p>
<p> Description: <input type="text" name="description" ></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
`
const taskListTmplHTML = `
<html>
<body>
<p>Task List</p>
{{range .}}
<p>{{.Name}} - {{.Description}}</p>
{{end}}
<p><a href="/create">Create task</a> </p>
</body>
</html>
`
var taskListTemplate = template.Must(template.New("taskList").Parse(taskListTmplHTML))
func init() {
http.HandleFunc("/", index)
http.HandleFunc("/create", create)
http.HandleFunc("/save", save)
}
func index(w http.ResponseWriter, r *http.Request) {
q := datastore.NewQuery("tasks").
Order("-CreatedOn")
c := appengine.NewContext(r)
var tasks []Task
_, err := q.GetAll(c, &tasks)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
if err := taskListTemplate.Execute(w, tasks); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func create(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, taskForm)
}
func save(w http.ResponseWriter, r *http.Request) {
task := Task{
Name: r.FormValue("taskname"),
Description: r.FormValue("description"),
CreatedOn: time.Now(),
}
c := appengine.NewContext(r)
_, err := datastore.Put(c, datastore.NewIncompleteKey(c, "tasks", nil), &task)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusMovedPermanently)
}