| 1 |
// Copyright 2019 The Go Cloud Development Kit Authors |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// https://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
|
| 15 |
package main |
| 16 |
|
| 17 |
import ( |
| 18 |
"bytes" |
| 19 |
"context" |
| 20 |
"encoding/json" |
| 21 |
"fmt" |
| 22 |
"html/template" |
| 23 |
"io" |
| 24 |
"log" |
| 25 |
"net/http" |
| 26 |
"os" |
| 27 |
"path/filepath" |
| 28 |
"strings" |
| 29 |
"time" |
| 30 |
|
| 31 |
"gocloud.dev/blob" |
| 32 |
_ "gocloud.dev/blob/fileblob" |
| 33 |
"gocloud.dev/docstore" |
| 34 |
_ "gocloud.dev/docstore/memdocstore" |
| 35 |
"gocloud.dev/pubsub" |
| 36 |
_ "gocloud.dev/pubsub/mempubsub" |
| 37 |
"gocloud.dev/server" |
| 38 |
"gocloud.dev/server/requestlog" |
| 39 |
) |
| 40 |
|
| 41 |
// A frontend is a web server that takes image-processing orders. |
| 42 |
type frontend struct { |
| 43 |
requestTopic *pubsub.Topic |
| 44 |
bucket *blob.Bucket |
| 45 |
coll *docstore.Collection |
| 46 |
} |
| 47 |
|
| 48 |
var ( |
| 49 |
listTemplate *template.Template |
| 50 |
orderFormTemplate *template.Template |
| 51 |
) |
| 52 |
|
| 53 |
func init() { |
| 54 |
// Work around a bug in go test where -coverpkg=./... uses the wrong |
| 55 |
// working directory (golang.org/issue/33016). |
| 56 |
dir, err := os.Getwd() |
| 57 |
if err != nil { |
| 58 |
log.Fatal(err) |
| 59 |
} |
| 60 |
if filepath.Base(dir) != "order" { |
| 61 |
// The bug puts us in a sibling directory. |
| 62 |
log.Printf("working around #33016, which put us in %s", dir) |
| 63 |
dir = filepath.Join(filepath.Dir(dir), "order") |
| 64 |
} |
| 65 |
listTemplate = template.Must(template.ParseFiles(filepath.Join(dir, "list.htmlt"))) |
| 66 |
orderFormTemplate = template.Must(template.ParseFiles(filepath.Join(dir, "order-form.htmlt"))) |
| 67 |
} |
| 68 |
|
| 69 |
// run starts the server on port and runs it indefinitely. |
| 70 |
func (f *frontend) run(ctx context.Context, port int) error { |
| 71 |
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") }) |
| 72 |
http.HandleFunc("/style.css", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "style.css") }) |
| 73 |
http.HandleFunc("/orders/", wrapHTTPError(f.listOrders)) |
| 74 |
http.HandleFunc("/orders/new", wrapHTTPError(f.orderForm)) |
| 75 |
http.HandleFunc("/createOrder", wrapHTTPError(f.createOrder)) |
| 76 |
http.HandleFunc("/show/", wrapHTTPError(f.showImage)) |
| 77 |
|
| 78 |
rl := requestlog.NewNCSALogger(os.Stdout, func(err error) { fmt.Fprintf(os.Stderr, "%v\n", err) }) |
| 79 |
s := server.New(nil, &server.Options{ |
| 80 |
RequestLogger: rl, |
| 81 |
}) |
| 82 |
return s.ListenAndServe(fmt.Sprintf(":%d", port)) |
| 83 |
} |
| 84 |
|
| 85 |
// wrapHTTPError turns handlers that return error into ordinary http.Handlers, |
| 86 |
// by calling http.Error on non-nil errors. |
| 87 |
func wrapHTTPError(f func(http.ResponseWriter, *http.Request) error) func(http.ResponseWriter, *http.Request) { |
| 88 |
return func(w http.ResponseWriter, r *http.Request) { |
| 89 |
if err := f(w, r); err != nil { |
| 90 |
http.Error(w, err.Error(), http.StatusInternalServerError) |
| 91 |
} |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
// orderForm serves a page that lets the user input a new order. |
| 96 |
func (*frontend) orderForm(w http.ResponseWriter, r *http.Request) error { |
| 97 |
if r.Method != "GET" { |
| 98 |
http.Error(w, "bad method for orderForm: want GET", http.StatusBadRequest) |
| 99 |
return nil |
| 100 |
} |
| 101 |
return executeTemplate(orderFormTemplate, nil, w) |
| 102 |
} |
| 103 |
|
| 104 |
// createOrder handles a submitted order form. |
| 105 |
func (f *frontend) createOrder(w http.ResponseWriter, r *http.Request) error { |
| 106 |
if r.Method != "POST" { |
| 107 |
http.Error(w, "bad method for createOrder: want POST", http.StatusBadRequest) |
| 108 |
return nil |
| 109 |
} |
| 110 |
email := r.FormValue("email") |
| 111 |
if email == "" { |
| 112 |
http.Error(w, "email missing", http.StatusBadRequest) |
| 113 |
return nil |
| 114 |
} |
| 115 |
|
| 116 |
file, _, err := r.FormFile("file") |
| 117 |
if err != nil { |
| 118 |
return err |
| 119 |
} |
| 120 |
defer file.Close() |
| 121 |
if _, err := f.doCreateOrder(r.Context(), email, file, time.Now()); err != nil { |
| 122 |
return err |
| 123 |
} |
| 124 |
fmt.Fprintln(w, "Order received. Thank you.") |
| 125 |
return nil |
| 126 |
} |
| 127 |
|
| 128 |
// doCreateOrder creates a new order. |
| 129 |
// It is passed the customer's email address, an io.Reader for reading the input |
| 130 |
// image, and the current time. |
| 131 |
// It creates an Order in the database and sends an OrderRequest over the pub/sub topic. |
| 132 |
// It returns the order ID it generates, for testing. |
| 133 |
func (f *frontend) doCreateOrder(ctx context.Context, email string, file io.Reader, now time.Time) (id string, err error) { |
| 134 |
// Assign an ID for the order here, rather than in the processor. |
| 135 |
// That allows the processor to detect duplicate pub/sub messages. |
| 136 |
id = f.newID() |
| 137 |
req := &OrderRequest{ |
| 138 |
ID: id, |
| 139 |
InImage: id + "-in", |
| 140 |
Email: email, |
| 141 |
CreateTime: now, |
| 142 |
} |
| 143 |
|
| 144 |
// Copy the uploaded input file to the bucket. |
| 145 |
w, err := f.bucket.NewWriter(ctx, req.InImage, nil) |
| 146 |
if err != nil { |
| 147 |
return "", err |
| 148 |
} |
| 149 |
_, err = io.Copy(w, file) |
| 150 |
if err != nil { |
| 151 |
_ = w.Close() // ignore error |
| 152 |
return "", err |
| 153 |
} |
| 154 |
if err := w.Close(); err != nil { |
| 155 |
return "", err |
| 156 |
} |
| 157 |
|
| 158 |
defer func() { |
| 159 |
// if we can't send the request, the image will never be processed. |
| 160 |
// Try to delete it. |
| 161 |
if err != nil { |
| 162 |
if err := f.bucket.Delete(ctx, req.InImage); err != nil { |
| 163 |
log.Printf("deleting orphan image %q: %v", req.InImage, err) |
| 164 |
} |
| 165 |
} |
| 166 |
}() |
| 167 |
|
| 168 |
// Publish the new order. |
| 169 |
bytes, err := json.Marshal(req) |
| 170 |
if err != nil { |
| 171 |
return "", err |
| 172 |
} |
| 173 |
if err := f.requestTopic.Send(ctx, &pubsub.Message{Body: bytes}); err != nil { |
| 174 |
return "", err |
| 175 |
} |
| 176 |
return id, nil |
| 177 |
} |
| 178 |
|
| 179 |
// listOrders lists all the orders in the database. |
| 180 |
func (f *frontend) listOrders(w http.ResponseWriter, r *http.Request) error { |
| 181 |
if r.Method != "GET" { |
| 182 |
http.Error(w, "bad method for listOrders: want GET", http.StatusBadRequest) |
| 183 |
return nil |
| 184 |
} |
| 185 |
ctx := r.Context() |
| 186 |
iter := f.coll.Query().Get(ctx) |
| 187 |
var orders []*Order |
| 188 |
for { |
| 189 |
var ord Order |
| 190 |
err := iter.Next(ctx, &ord) |
| 191 |
if err == io.EOF { |
| 192 |
break |
| 193 |
} |
| 194 |
if err != nil { |
| 195 |
return err |
| 196 |
} |
| 197 |
orders = append(orders, &ord) |
| 198 |
} |
| 199 |
return executeTemplate(listTemplate, orders, w) |
| 200 |
} |
| 201 |
|
| 202 |
func (f *frontend) showImage(w http.ResponseWriter, r *http.Request) error { |
| 203 |
objKey := strings.TrimPrefix(r.URL.Path, "/show/") |
| 204 |
reader, err := f.bucket.NewReader(r.Context(), objKey, nil) |
| 205 |
if err != nil { |
| 206 |
http.Error(w, fmt.Sprintf("file %q not found", objKey), http.StatusNotFound) |
| 207 |
return nil |
| 208 |
} |
| 209 |
defer reader.Close() |
| 210 |
if _, err := io.Copy(w, reader); err != nil { |
| 211 |
log.Printf("copy from %q failed: %v", objKey, err) |
| 212 |
} |
| 213 |
return nil |
| 214 |
} |
| 215 |
|
| 216 |
// newID creates a new unique ID for an incoming order. It uses the current |
| 217 |
// second, formatted in a readable way. The resulting IDs sort nicely and are |
| 218 |
// easy to read, but of course are not suitable for production because there |
| 219 |
// could be more than one request in a second and because the clock can be |
| 220 |
// reset to the past, resulting in duplicates. |
| 221 |
func (f *frontend) newID() string { |
| 222 |
return time.Now().Format("060102-150405") |
| 223 |
} |
| 224 |
|
| 225 |
// executeTemplate executes t into a buffer using data, and if that succeeds it |
| 226 |
// writes the bytes to w. |
| 227 |
func executeTemplate(t *template.Template, data any, w http.ResponseWriter) error { |
| 228 |
var buf bytes.Buffer |
| 229 |
if err := t.Execute(&buf, data); err != nil { |
| 230 |
return err |
| 231 |
} |
| 232 |
if _, err := buf.WriteTo(w); err != nil { |
| 233 |
log.Printf("write failed: %v", err) |
| 234 |
} |
| 235 |
return nil |
| 236 |
} |