This repository has been archived by the owner on Nov 12, 2017. It is now read-only.
/
app.go
86 lines (67 loc) · 1.65 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
package app
import (
"html/template"
"net/http"
"strconv"
"google.golang.org/appengine"
"github.com/Bogdanp/anom"
)
// Post is the model struct for blog posts.
type Post struct {
anom.Meta
Title string
Content string
}
func init() {
http.HandleFunc("/", listPosts)
http.HandleFunc("/view/", viewPost)
http.HandleFunc("/delete/", deletePost)
}
func listPosts(rw http.ResponseWriter, req *http.Request) {
ctx := appengine.NewContext(req)
if req.Method == http.MethodPost {
p := &Post{
Title: req.PostFormValue("title"),
Content: req.PostFormValue("content"),
}
assert(anom.Put(ctx, p))
http.Redirect(rw, req, "/", http.StatusFound)
return
}
var posts []*Post
keys, err := anom.Query("Post").GetAll(ctx, &posts)
assert(err)
for i, p := range posts {
p.Key = keys[i]
}
renderTemplate(rw, "list.tmpl", posts)
}
func viewPost(rw http.ResponseWriter, req *http.Request) {
var p Post
ctx := appengine.NewContext(req)
sid := req.URL.Path[len("/view/"):]
id, err := strconv.ParseInt(sid, 10, 64)
assert(err)
assert(anom.Get(ctx, &p, anom.WithIntID(ctx, id)))
renderTemplate(rw, "post.tmpl", &p)
}
func deletePost(rw http.ResponseWriter, req *http.Request) {
var p Post
ctx := appengine.NewContext(req)
sid := req.URL.Path[len("/delete/"):]
id, err := strconv.ParseInt(sid, 10, 64)
assert(err)
assert(anom.Get(ctx, &p, anom.WithIntID(ctx, id)))
assert(anom.Delete(ctx, &p))
http.Redirect(rw, req, "/", http.StatusFound)
}
func renderTemplate(rw http.ResponseWriter, f string, d interface{}) {
t, err := template.ParseFiles(f)
assert(err)
assert(t.Execute(rw, d))
}
func assert(err error) {
if err != nil {
panic(err)
}
}