-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
main.go
336 lines (287 loc) · 9.93 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
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
333
334
335
336
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The bookshelf command starts the bookshelf server, a sample app
// demonstrating several Google Cloud APIs, including App Engine, Firestore, and
// Cloud Storage.
// See https://cloud.google.com/go/getting-started/tutorial-app.
package main
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"runtime/debug"
"cloud.google.com/go/errorreporting"
"cloud.google.com/go/firestore"
"cloud.google.com/go/storage"
"github.com/gofrs/uuid"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
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"
}
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
log.Fatal("GOOGLE_CLOUD_PROJECT must be set")
}
ctx := context.Background()
client, err := firestore.NewClient(ctx, projectID)
if err != nil {
log.Fatalf("firestore.NewClient: %v", err)
}
db, err := newFirestoreDB(client)
if err != nil {
log.Fatalf("newFirestoreDB: %v", err)
}
b, err := NewBookshelf(projectID, db)
if err != nil {
log.Fatalf("NewBookshelf: %v", err)
}
b.registerHandlers()
log.Printf("Listening on localhost:%s", port)
if err := http.ListenAndServe(":"+port, nil); err != nil {
log.Fatal(err)
}
}
func (b *Bookshelf) registerHandlers() {
// Use gorilla/mux for rich routing.
// See https://www.gorillatoolkit.org/pkg/mux.
r := mux.NewRouter()
r.Handle("/", http.RedirectHandler("/books", http.StatusFound))
r.Methods("GET").Path("/books").
Handler(appHandler(b.listHandler))
r.Methods("GET").Path("/books/add").
Handler(appHandler(b.addFormHandler))
r.Methods("GET").Path("/books/{id:[0-9a-zA-Z_\\-]+}").
Handler(appHandler(b.detailHandler))
r.Methods("GET").Path("/books/{id:[0-9a-zA-Z_\\-]+}/edit").
Handler(appHandler(b.editFormHandler))
r.Methods("POST").Path("/books").
Handler(appHandler(b.createHandler))
r.Methods("POST", "PUT").Path("/books/{id:[0-9a-zA-Z_\\-]+}").
Handler(appHandler(b.updateHandler))
r.Methods("POST").Path("/books/{id:[0-9a-zA-Z_\\-]+}:delete").
Handler(appHandler(b.deleteHandler)).Name("delete")
r.Methods("GET").Path("/logs").Handler(appHandler(b.sendLog))
r.Methods("GET").Path("/errors").Handler(appHandler(b.sendError))
// 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(b.logWriter, r))
}
// listHandler displays a list with summaries of books in the database.
func (b *Bookshelf) listHandler(w http.ResponseWriter, r *http.Request) *appError {
ctx := r.Context()
books, err := b.DB.ListBooks(ctx)
if err != nil {
return b.appErrorf(r, err, "could not list books: %v", err)
}
return listTmpl.Execute(b, w, r, books)
}
// bookFromRequest retrieves a book from the database given a book ID in the
// URL's path.
func (b *Bookshelf) bookFromRequest(r *http.Request) (*Book, error) {
ctx := r.Context()
id := mux.Vars(r)["id"]
if id == "" {
return nil, errors.New("no book with empty ID")
}
book, err := b.DB.GetBook(ctx, id)
if err != nil {
return nil, fmt.Errorf("could not find book: %w", err)
}
return book, nil
}
// detailHandler displays the details of a given book.
func (b *Bookshelf) detailHandler(w http.ResponseWriter, r *http.Request) *appError {
book, err := b.bookFromRequest(r)
if err != nil {
return b.appErrorf(r, err, "%v", err)
}
return detailTmpl.Execute(b, w, r, book)
}
// addFormHandler displays a form that captures details of a new book to add to
// the database.
func (b *Bookshelf) addFormHandler(w http.ResponseWriter, r *http.Request) *appError {
return editTmpl.Execute(b, w, r, nil)
}
// editFormHandler displays a form that allows the user to edit the details of
// a given book.
func (b *Bookshelf) editFormHandler(w http.ResponseWriter, r *http.Request) *appError {
book, err := b.bookFromRequest(r)
if err != nil {
return b.appErrorf(r, err, "%v", err)
}
return editTmpl.Execute(b, w, r, book)
}
// bookFromForm populates the fields of a Book from form values
// (see templates/edit.html).
func (b *Bookshelf) bookFromForm(r *http.Request) (*Book, error) {
ctx := r.Context()
imageURL, err := b.uploadFileFromForm(ctx, r)
if err != nil {
return nil, fmt.Errorf("could not upload file: %w", err)
}
if imageURL == "" {
imageURL = r.FormValue("imageURL")
}
book := &Book{
Title: r.FormValue("title"),
Author: r.FormValue("author"),
PublishedDate: r.FormValue("publishedDate"),
ImageURL: imageURL,
Description: r.FormValue("description"),
}
return book, nil
}
// [START getting_started_bookshelf_storage]
// uploadFileFromForm uploads a file if it's present in the "image" form field.
func (b *Bookshelf) uploadFileFromForm(ctx context.Context, 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 b.StorageBucket == nil {
return "", errors.New("storage bucket is missing: check bookshelf.go")
}
if _, err := b.StorageBucket.Attrs(ctx); err != nil {
if err == storage.ErrBucketNotExist {
return "", fmt.Errorf("bucket %q does not exist: check bookshelf.go", b.StorageBucketName)
}
return "", fmt.Errorf("could not get bucket: %w", err)
}
// random filename, retaining existing extension.
name := uuid.Must(uuid.NewV4()).String() + path.Ext(fh.Filename)
w := b.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, b.StorageBucketName, name), nil
}
// [END getting_started_bookshelf_storage]
// createHandler adds a book to the database.
func (b *Bookshelf) createHandler(w http.ResponseWriter, r *http.Request) *appError {
ctx := r.Context()
book, err := b.bookFromForm(r)
if err != nil {
return b.appErrorf(r, err, "could not parse book from form: %v", err)
}
id, err := b.DB.AddBook(ctx, book)
if err != nil {
return b.appErrorf(r, err, "could not save book: %v", err)
}
http.Redirect(w, r, fmt.Sprintf("/books/%s", id), http.StatusFound)
return nil
}
// updateHandler updates the details of a given book.
func (b *Bookshelf) updateHandler(w http.ResponseWriter, r *http.Request) *appError {
ctx := r.Context()
id := mux.Vars(r)["id"]
if id == "" {
return b.appErrorf(r, errors.New("no book with empty ID"), "no book with empty ID")
}
book, err := b.bookFromForm(r)
if err != nil {
return b.appErrorf(r, err, "could not parse book from form: %v", err)
}
book.ID = id
if err := b.DB.UpdateBook(ctx, book); err != nil {
return b.appErrorf(r, err, "UpdateBook: %v", err)
}
http.Redirect(w, r, fmt.Sprintf("/books/%s", book.ID), http.StatusFound)
return nil
}
// deleteHandler deletes a given book.
func (b *Bookshelf) deleteHandler(w http.ResponseWriter, r *http.Request) *appError {
ctx := r.Context()
id := mux.Vars(r)["id"]
if err := b.DB.DeleteBook(ctx, id); err != nil {
return b.appErrorf(r, err, "DeleteBook: %v", err)
}
http.Redirect(w, r, "/books", http.StatusFound)
return nil
}
// sendLog logs a message.
//
// See https://cloud.google.com/logging/docs/setup/go for how to use the
// Stackdriver logging client. Output to stdout and stderr is automaticaly
// sent to Stackdriver when running on App Engine.
func (b *Bookshelf) sendLog(w http.ResponseWriter, r *http.Request) *appError {
fmt.Fprintln(b.logWriter, "Hey, you triggered a custom log entry. Good job!")
fmt.Fprintln(w, `<html>Log sent! Check the <a href="http://console.cloud.google.com/logs">logging section of the Cloud Console</a>.</html>`)
return nil
}
// sendError triggers an error that is sent to Error Reporting.
func (b *Bookshelf) sendError(w http.ResponseWriter, r *http.Request) *appError {
msg := `<html>Logging an error. Check <a href="http://console.cloud.google.com/errors">Error Reporting</a> (it may take a minute or two for the error to appear).</html>`
err := errors.New("uh oh! an error occurred")
return b.appErrorf(r, err, msg)
}
// https://blog.golang.org/error-handling-and-go
type appHandler func(http.ResponseWriter, *http.Request) *appError
type appError struct {
err error
message string
code int
req *http.Request
b *Bookshelf
stack []byte
}
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if e := fn(w, r); e != nil { // e is *appError, not os.Error.
fmt.Fprintf(e.b.logWriter, "Handler error (reported to Error Reporting): status code: %d, message: %s, underlying err: %+v\n", e.code, e.message, e.err)
w.WriteHeader(e.code)
fmt.Fprint(w, e.message)
e.b.errorClient.Report(errorreporting.Entry{
Error: e.err,
Req: r,
Stack: e.stack,
})
e.b.errorClient.Flush()
}
}
func (b *Bookshelf) appErrorf(r *http.Request, err error, format string, v ...interface{}) *appError {
return &appError{
err: err,
message: fmt.Sprintf(format, v...),
code: 500,
req: r,
b: b,
stack: debug.Stack(),
}
}