/
main.go
121 lines (100 loc) · 2.64 KB
/
main.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
// Copyright 2018 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"html/template"
"net/http"
"google.golang.org/appengine"
// [START imports]
"time"
"google.golang.org/appengine/datastore"
"google.golang.org/appengine/log"
// [END imports]
)
var (
indexTemplate = template.Must(template.ParseFiles("index.html"))
)
// [START post_struct]
type Post struct {
Author string
Message string
Posted time.Time
}
// [END post_struct]
type templateParams struct {
Notice string
Name string
// [START added_templateParams_fields]
Message string
Posts []Post
// [END added_templateParams_fields]
}
func main() {
http.HandleFunc("/", indexHandler)
appengine.Main()
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Redirect(w, r, "/", http.StatusFound)
return
}
// [START new_context]
ctx := appengine.NewContext(r)
// [END new_context]
params := templateParams{}
// [START new_query]
q := datastore.NewQuery("Post").Order("-Posted").Limit(20)
// [END new_query]
// [START get_posts]
if _, err := q.GetAll(ctx, ¶ms.Posts); err != nil {
log.Errorf(ctx, "Getting posts: %v", err)
w.WriteHeader(http.StatusInternalServerError)
params.Notice = "Couldn't get latest posts. Refresh?"
indexTemplate.Execute(w, params)
return
}
// [END get_posts]
if r.Method == "GET" {
indexTemplate.Execute(w, params)
return
}
// It's a POST request, so handle the form submission.
// [START new_post]
post := Post{
Author: r.FormValue("name"),
Message: r.FormValue("message"),
Posted: time.Now(),
}
// [END new_post]
if post.Author == "" {
post.Author = "Anonymous Gopher"
}
params.Name = post.Author
if post.Message == "" {
w.WriteHeader(http.StatusBadRequest)
params.Notice = "No message provided"
indexTemplate.Execute(w, params)
return
}
// [START new_key]
key := datastore.NewIncompleteKey(ctx, "Post", nil)
// [END new_key]
// [START add_post]
if _, err := datastore.Put(ctx, key, &post); err != nil {
log.Errorf(ctx, "datastore.Put: %v", err)
w.WriteHeader(http.StatusInternalServerError)
params.Notice = "Couldn't add new post. Try again?"
params.Message = post.Message // Preserve their message so they can try again.
indexTemplate.Execute(w, params)
return
}
// [END add_post]
// Prepend the post that was just added.
// [START prepend_post]
params.Posts = append([]Post{post}, params.Posts...)
// [END prepend_post]
params.Notice = fmt.Sprintf("Thank you for your submission, %s!", post.Author)
indexTemplate.Execute(w, params)
}