-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblog.go
103 lines (88 loc) · 2.14 KB
/
blog.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
package main
import (
"fmt"
"labix.org/v2/mgo"
//"labix.org/v2/mgo/bson"
"net/http"
"text/template"
"time"
)
type Post struct {
Content string
Date time.Time
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
//array of Posts
entries := []Post{}
err := posts.Find(nil).Limit(12).Sort("-date").All(&entries)
if err != nil {
fmt.Fprintf(w, "err: %s!", err)
http.NotFound(w, r)
}
ctx := map[string]interface{} {
"posts":entries,
}
indexTemplate.Execute(w, ctx)
}
func createHandler(w http.ResponseWriter, r *http.Request) {
// hardcore security right here ;-)
if r.Method == "POST" && (r.FormValue("pw") == "pw") {
//fmt.Fprintf(w, "%s", r.FormValue("content"))
content := r.FormValue("content")
newPost := &Post{Content:content, Date: time.Now()}
//fmt.Fprintf(w, "%s", newPost)
//insert new Post
posts.Insert(newPost)
http.Redirect(w, r, "/", 302)
} else {
//if its a GET, show the input form
createTemplate.Execute(w, http.StatusFound/*302*/)
}
}
var posts *mgo.Collection
func main() {
session, err := mgo.Dial("localhost")
if err != nil {
panic(err)
}
defer session.Close()
// Optional. Switch the session to a monotonic behavior.
//session.SetMode(mgo.Monotonic, true)
posts = session.DB("blog").C("post")
result := Post{}
err = posts.Find(nil).One(&result)
if err != nil {
panic(err)
}
http.HandleFunc("/", indexHandler)
http.HandleFunc("/create", createHandler)
http.ListenAndServe(":8081", nil)
}
var indexTemplate = template.Must(template.New("index").Parse(`
<html>
<body>
<h2>Stuff... <a href="mailto:[email protected]">[email protected]</a></h2>
<ul>
{{range .posts}}
<li>
{{.Content}}
</li>
{{end}}
</ul>
</body>
</html>
`))
var createTemplate = template.Must(template.New("create").Parse(`
<html>
<body>
<h2>Stuff... <a href="mailto:[email protected]">[email protected]</a></h2>
<div>
<form action="create" method="post">
<textarea name="content" rows="4" cols="40"><a href=""></a></textarea>
<input type="input" name="pw" value="pw">
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
`))