forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
332 lines (282 loc) · 9.27 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
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// Copyright 2015 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.
// Sample bookshelf is a fully-featured app demonstrating several Google Cloud APIs, including Datastore, Cloud SQL, Cloud Storage.
// See https://cloud.google.com/go/getting-started/tutorial-app
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"strconv"
"cloud.google.com/go/pubsub"
"cloud.google.com/go/storage"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
uuid "github.com/satori/go.uuid"
"github.com/GoogleCloudPlatform/golang-samples/getting-started/bookshelf"
)
var (
// See template.go
listTmpl = parseTemplate("list.html")
editTmpl = parseTemplate("edit.html")
detailTmpl = parseTemplate("detail.html")
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
registerHandlers()
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}
func registerHandlers() {
// Use gorilla/mux for rich routing.
// See http://www.gorillatoolkit.org/pkg/mux
r := mux.NewRouter()
r.Handle("/", http.RedirectHandler("/books", http.StatusFound))
r.Methods("GET").Path("/books").
Handler(appHandler(listHandler))
r.Methods("GET").Path("/books/mine").
Handler(appHandler(listMineHandler))
r.Methods("GET").Path("/books/{id:[0-9]+}").
Handler(appHandler(detailHandler))
r.Methods("GET").Path("/books/add").
Handler(appHandler(addFormHandler))
r.Methods("GET").Path("/books/{id:[0-9]+}/edit").
Handler(appHandler(editFormHandler))
r.Methods("POST").Path("/books").
Handler(appHandler(createHandler))
r.Methods("POST", "PUT").Path("/books/{id:[0-9]+}").
Handler(appHandler(updateHandler))
r.Methods("POST").Path("/books/{id:[0-9]+}:delete").
Handler(appHandler(deleteHandler)).Name("delete")
// The following handlers are defined in auth.go and used in the
// "Authenticating Users" part of the Getting Started guide.
r.Methods("GET").Path("/login").
Handler(appHandler(loginHandler))
r.Methods("POST").Path("/logout").
Handler(appHandler(logoutHandler))
r.Methods("GET").Path("/oauth2callback").
Handler(appHandler(oauthCallbackHandler))
// Respond to App Engine and Compute Engine health checks.
// Indicate the server is healthy.
r.Methods("GET").Path("/_ah/health").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
// [START request_logging]
// Delegate all of the HTTP routing and serving to the gorilla/mux router.
// Log all requests using the standard Apache format.
http.Handle("/", handlers.CombinedLoggingHandler(os.Stderr, r))
// [END request_logging]
}
// listHandler displays a list with summaries of books in the database.
func listHandler(w http.ResponseWriter, r *http.Request) *appError {
books, err := bookshelf.DB.ListBooks()
if err != nil {
return appErrorf(err, "could not list books: %v", err)
}
return listTmpl.Execute(w, r, books)
}
// listMineHandler displays a list of books created by the currently
// authenticated user.
func listMineHandler(w http.ResponseWriter, r *http.Request) *appError {
user := profileFromSession(r)
if user == nil {
http.Redirect(w, r, "/login?redirect=/books/mine", http.StatusFound)
return nil
}
books, err := bookshelf.DB.ListBooksCreatedBy(user.ID)
if err != nil {
return appErrorf(err, "could not list books: %v", err)
}
return listTmpl.Execute(w, r, books)
}
// bookFromRequest retrieves a book from the database given a book ID in the
// URL's path.
func bookFromRequest(r *http.Request) (*bookshelf.Book, error) {
id, err := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
if err != nil {
return nil, fmt.Errorf("bad book id: %v", err)
}
book, err := bookshelf.DB.GetBook(id)
if err != nil {
return nil, fmt.Errorf("could not find book: %v", err)
}
return book, nil
}
// detailHandler displays the details of a given book.
func detailHandler(w http.ResponseWriter, r *http.Request) *appError {
book, err := bookFromRequest(r)
if err != nil {
return appErrorf(err, "%v", err)
}
return detailTmpl.Execute(w, r, book)
}
// addFormHandler displays a form that captures details of a new book to add to
// the database.
func addFormHandler(w http.ResponseWriter, r *http.Request) *appError {
return editTmpl.Execute(w, r, nil)
}
// editFormHandler displays a form that allows the user to edit the details of
// a given book.
func editFormHandler(w http.ResponseWriter, r *http.Request) *appError {
book, err := bookFromRequest(r)
if err != nil {
return appErrorf(err, "%v", err)
}
return editTmpl.Execute(w, r, book)
}
// bookFromForm populates the fields of a Book from form values
// (see templates/edit.html).
func bookFromForm(r *http.Request) (*bookshelf.Book, error) {
imageURL, err := uploadFileFromForm(r)
if err != nil {
return nil, fmt.Errorf("could not upload file: %v", err)
}
if imageURL == "" {
imageURL = r.FormValue("imageURL")
}
book := &bookshelf.Book{
Title: r.FormValue("title"),
Author: r.FormValue("author"),
PublishedDate: r.FormValue("publishedDate"),
ImageURL: imageURL,
Description: r.FormValue("description"),
CreatedBy: r.FormValue("createdBy"),
CreatedByID: r.FormValue("createdByID"),
}
// If the form didn't carry the user information for the creator, populate it
// from the currently logged in user (or mark as anonymous).
if book.CreatedByID == "" {
user := profileFromSession(r)
if user != nil {
// Logged in.
book.CreatedBy = user.DisplayName
book.CreatedByID = user.ID
} else {
// Not logged in.
book.SetCreatorAnonymous()
}
}
return book, nil
}
// uploadFileFromForm uploads a file if it's present in the "image" form field.
func uploadFileFromForm(r *http.Request) (url string, err error) {
f, fh, err := r.FormFile("image")
if err == http.ErrMissingFile {
return "", nil
}
if err != nil {
return "", err
}
if bookshelf.StorageBucket == nil {
return "", errors.New("storage bucket is missing - check config.go")
}
// random filename, retaining existing extension.
name := uuid.Must(uuid.NewV4()).String() + path.Ext(fh.Filename)
ctx := context.Background()
w := bookshelf.StorageBucket.Object(name).NewWriter(ctx)
// Warning: storage.AllUsers gives public read access to anyone.
w.ACL = []storage.ACLRule{{Entity: storage.AllUsers, Role: storage.RoleReader}}
w.ContentType = fh.Header.Get("Content-Type")
// Entries are immutable, be aggressive about caching (1 day).
w.CacheControl = "public, max-age=86400"
if _, err := io.Copy(w, f); err != nil {
return "", err
}
if err := w.Close(); err != nil {
return "", err
}
const publicURL = "https://storage.googleapis.com/%s/%s"
return fmt.Sprintf(publicURL, bookshelf.StorageBucketName, name), nil
}
// createHandler adds a book to the database.
func createHandler(w http.ResponseWriter, r *http.Request) *appError {
book, err := bookFromForm(r)
if err != nil {
return appErrorf(err, "could not parse book from form: %v", err)
}
id, err := bookshelf.DB.AddBook(book)
if err != nil {
return appErrorf(err, "could not save book: %v", err)
}
go publishUpdate(id)
http.Redirect(w, r, fmt.Sprintf("/books/%d", id), http.StatusFound)
return nil
}
// updateHandler updates the details of a given book.
func updateHandler(w http.ResponseWriter, r *http.Request) *appError {
id, err := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
if err != nil {
return appErrorf(err, "bad book id: %v", err)
}
book, err := bookFromForm(r)
if err != nil {
return appErrorf(err, "could not parse book from form: %v", err)
}
book.ID = id
err = bookshelf.DB.UpdateBook(book)
if err != nil {
return appErrorf(err, "could not save book: %v", err)
}
go publishUpdate(book.ID)
http.Redirect(w, r, fmt.Sprintf("/books/%d", book.ID), http.StatusFound)
return nil
}
// deleteHandler deletes a given book.
func deleteHandler(w http.ResponseWriter, r *http.Request) *appError {
id, err := strconv.ParseInt(mux.Vars(r)["id"], 10, 64)
if err != nil {
return appErrorf(err, "bad book id: %v", err)
}
err = bookshelf.DB.DeleteBook(id)
if err != nil {
return appErrorf(err, "could not delete book: %v", err)
}
http.Redirect(w, r, "/books", http.StatusFound)
return nil
}
// publishUpdate notifies Pub/Sub subscribers that the book identified with
// the given ID has been added/modified.
func publishUpdate(bookID int64) {
if bookshelf.PubsubClient == nil {
return
}
ctx := context.Background()
b, err := json.Marshal(bookID)
if err != nil {
return
}
topic := bookshelf.PubsubClient.Topic(bookshelf.PubsubTopicID)
_, err = topic.Publish(ctx, &pubsub.Message{Data: b}).Get(ctx)
log.Printf("Published update to Pub/Sub for Book ID %d: %v", bookID, err)
}
// http://blog.golang.org/error-handling-and-go
type appHandler func(http.ResponseWriter, *http.Request) *appError
type appError struct {
Error error
Message string
Code int
}
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *appError, not os.Error.
log.Printf("Handler error: status code: %d, message: %s, underlying err: %#v",
e.Code, e.Message, e.Error)
http.Error(w, e.Message, e.Code)
}
}
func appErrorf(err error, format string, v ...interface{}) *appError {
return &appError{
Error: err,
Message: fmt.Sprintf(format, v...),
Code: 500,
}
}