| 1 |
// Copyright 2018 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 |
// guestbook is a sample application that records visitors' messages, displays a |
| 16 |
// cloud banner, and an administrative message. |
| 17 |
package main |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"context" |
| 22 |
"database/sql" |
| 23 |
"flag" |
| 24 |
"html/template" |
| 25 |
"io" |
| 26 |
"log" |
| 27 |
"net/http" |
| 28 |
"strconv" |
| 29 |
"time" |
| 30 |
|
| 31 |
"github.com/google/wire" |
| 32 |
"github.com/gorilla/mux" |
| 33 |
"gocloud.dev/blob" |
| 34 |
"gocloud.dev/gcerrors" |
| 35 |
"gocloud.dev/runtimevar" |
| 36 |
|
| 37 |
"gocloud.dev/server" |
| 38 |
"gocloud.dev/server/health" |
| 39 |
"gocloud.dev/server/health/sqlhealth" |
| 40 |
) |
| 41 |
|
| 42 |
type cliFlags struct { |
| 43 |
bucket string |
| 44 |
dbHost string |
| 45 |
dbName string |
| 46 |
dbUser string |
| 47 |
dbPassword string |
| 48 |
motdVar string |
| 49 |
motdVarWaitTime time.Duration |
| 50 |
|
| 51 |
// GCP only. |
| 52 |
cloudSQLRegion string |
| 53 |
runtimeConfigName string |
| 54 |
} |
| 55 |
|
| 56 |
var envFlag string |
| 57 |
|
| 58 |
func main() { |
| 59 |
// Determine environment to set up based on flag. |
| 60 |
cf := new(cliFlags) |
| 61 |
flag.StringVar(&envFlag, "env", "local", "environment to run under (gcp, aws, azure, or local)") |
| 62 |
addr := flag.String("listen", ":8080", "port to listen for HTTP on") |
| 63 |
flag.StringVar(&cf.bucket, "bucket", "", "bucket name") |
| 64 |
flag.StringVar(&cf.dbHost, "db_host", "", "database host or Cloud SQL instance name") |
| 65 |
flag.StringVar(&cf.dbName, "db_name", "guestbook", "database name") |
| 66 |
flag.StringVar(&cf.dbUser, "db_user", "guestbook", "database user") |
| 67 |
flag.StringVar(&cf.dbPassword, "db_password", "", "database user password") |
| 68 |
flag.StringVar(&cf.motdVar, "motd_var", "", "message of the day variable location") |
| 69 |
flag.DurationVar(&cf.motdVarWaitTime, "motd_var_wait_time", 5*time.Second, "polling frequency of message of the day") |
| 70 |
flag.StringVar(&cf.cloudSQLRegion, "cloud_sql_region", "", "region of the Cloud SQL instance (GCP only)") |
| 71 |
flag.StringVar(&cf.runtimeConfigName, "runtime_config", "", "Runtime Configurator config resource (GCP only)") |
| 72 |
flag.Parse() |
| 73 |
|
| 74 |
ctx := context.Background() |
| 75 |
var srv *server.Server |
| 76 |
var cleanup func() |
| 77 |
var err error |
| 78 |
switch envFlag { |
| 79 |
case "gcp": |
| 80 |
srv, cleanup, err = setupGCP(ctx, cf) |
| 81 |
case "aws": |
| 82 |
srv, cleanup, err = setupAWS(ctx, cf) |
| 83 |
case "azure": |
| 84 |
if cf.dbHost == "" { |
| 85 |
cf.dbHost = "localhost" |
| 86 |
} |
| 87 |
if cf.dbPassword == "" { |
| 88 |
cf.dbPassword = "xyzzy" |
| 89 |
} |
| 90 |
srv, cleanup, err = setupAzure(ctx, cf) |
| 91 |
case "local": |
| 92 |
// The default MySQL instance is running on localhost |
| 93 |
// with this root password. |
| 94 |
if cf.dbHost == "" { |
| 95 |
cf.dbHost = "localhost" |
| 96 |
} |
| 97 |
if cf.dbPassword == "" { |
| 98 |
cf.dbPassword = "xyzzy" |
| 99 |
} |
| 100 |
srv, cleanup, err = setupLocal(ctx, cf) |
| 101 |
default: |
| 102 |
log.Fatalf("unknown -env=%s", envFlag) |
| 103 |
} |
| 104 |
if err != nil { |
| 105 |
log.Fatal(err) |
| 106 |
} |
| 107 |
defer cleanup() |
| 108 |
|
| 109 |
// Listen and serve HTTP. |
| 110 |
log.Printf("Running, connected to %q cloud", envFlag) |
| 111 |
log.Fatal(srv.ListenAndServe(*addr)) |
| 112 |
} |
| 113 |
|
| 114 |
// applicationSet is the Wire provider set for the Guestbook application that |
| 115 |
// does not depend on the underlying platform. |
| 116 |
var applicationSet = wire.NewSet( |
| 117 |
newApplication, |
| 118 |
appHealthChecks, |
| 119 |
newRouter, |
| 120 |
wire.Bind(new(http.Handler), new(*mux.Router)), |
| 121 |
) |
| 122 |
|
| 123 |
func newRouter(app *application) *mux.Router { |
| 124 |
r := mux.NewRouter() |
| 125 |
r.HandleFunc("/", app.index) |
| 126 |
r.HandleFunc("/sign", app.sign) |
| 127 |
r.HandleFunc("/blob/{key:.+}", app.serveBlob) |
| 128 |
return r |
| 129 |
} |
| 130 |
|
| 131 |
// application is the main server struct for Guestbook. It contains the state of |
| 132 |
// the most recently read message of the day. |
| 133 |
type application struct { |
| 134 |
db *sql.DB |
| 135 |
bucket *blob.Bucket |
| 136 |
motdVar *runtimevar.Variable |
| 137 |
} |
| 138 |
|
| 139 |
// newApplication creates a new application struct based on the backends and the message |
| 140 |
// of the day variable. |
| 141 |
func newApplication(db *sql.DB, bucket *blob.Bucket, motdVar *runtimevar.Variable) *application { |
| 142 |
return &application{ |
| 143 |
db: db, |
| 144 |
bucket: bucket, |
| 145 |
motdVar: motdVar, |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
// index serves the server's landing page. It lists the 100 most recent |
| 150 |
// greetings, shows a cloud environment banner, and displays the message of the |
| 151 |
// day. |
| 152 |
func (app *application) index(w http.ResponseWriter, r *http.Request) { |
| 153 |
var data struct { |
| 154 |
MOTD string |
| 155 |
Env string |
| 156 |
BannerSrc string |
| 157 |
Greetings []greeting |
| 158 |
} |
| 159 |
snap, err := app.motdVar.Latest(r.Context()) |
| 160 |
if err != nil { |
| 161 |
log.Println("index page error:", err) |
| 162 |
http.Error(w, "could not load motd", http.StatusInternalServerError) |
| 163 |
return |
| 164 |
} |
| 165 |
data.MOTD = snap.Value.(string) |
| 166 |
|
| 167 |
switch envFlag { |
| 168 |
case "gcp": |
| 169 |
data.Env = "GCP" |
| 170 |
data.BannerSrc = "/blob/gcp.png" |
| 171 |
case "aws": |
| 172 |
data.Env = "AWS" |
| 173 |
data.BannerSrc = "/blob/aws.png" |
| 174 |
case "azure": |
| 175 |
data.Env = "Azure" |
| 176 |
data.BannerSrc = "/blob/azure.png" |
| 177 |
case "local": |
| 178 |
data.Env = "Local" |
| 179 |
data.BannerSrc = "/blob/gophers.jpg" |
| 180 |
} |
| 181 |
|
| 182 |
const query = "SELECT content FROM (SELECT content, post_date FROM greetings ORDER BY post_date DESC LIMIT 100) AS recent_greetings ORDER BY post_date ASC;" |
| 183 |
q, err := app.db.QueryContext(r.Context(), query) |
| 184 |
if err != nil { |
| 185 |
log.Println("main page SQL error:", err) |
| 186 |
http.Error(w, "could not load greetings", http.StatusInternalServerError) |
| 187 |
return |
| 188 |
} |
| 189 |
defer q.Close() |
| 190 |
for q.Next() { |
| 191 |
var g greeting |
| 192 |
if err := q.Scan(&g.Content); err != nil { |
| 193 |
log.Println("main page SQL error:", err) |
| 194 |
http.Error(w, "could not load greetings", http.StatusInternalServerError) |
| 195 |
return |
| 196 |
} |
| 197 |
data.Greetings = append(data.Greetings, g) |
| 198 |
} |
| 199 |
if err := q.Err(); err != nil { |
| 200 |
log.Println("main page SQL error:", err) |
| 201 |
http.Error(w, "could not load greetings", http.StatusInternalServerError) |
| 202 |
return |
| 203 |
} |
| 204 |
buf := new(bytes.Buffer) |
| 205 |
if err := tmpl.Execute(buf, data); err != nil { |
| 206 |
log.Println("template error:", err) |
| 207 |
http.Error(w, "could not render page", http.StatusInternalServerError) |
| 208 |
return |
| 209 |
} |
| 210 |
w.Header().Set("Content-Type", "text/html; charset=utf-8") |
| 211 |
w.Header().Set("Content-Length", strconv.Itoa(buf.Len())) |
| 212 |
if _, err := w.Write(buf.Bytes()); err != nil { |
| 213 |
log.Println("writing response:", err) |
| 214 |
} |
| 215 |
} |
| 216 |
|
| 217 |
type greeting struct { |
| 218 |
Content string |
| 219 |
} |
| 220 |
|
| 221 |
var tmpl = template.Must(template.New("index.html").Parse(`<!DOCTYPE html> |
| 222 |
<title>Guestbook - {{.Env}}</title> |
| 223 |
<style type="text/css"> |
| 224 |
html, body { |
| 225 |
font-family: Helvetica, sans-serif; |
| 226 |
} |
| 227 |
blockquote { |
| 228 |
font-family: cursive, Helvetica, sans-serif; |
| 229 |
} |
| 230 |
.banner { |
| 231 |
height: 125px; |
| 232 |
width: 250px; |
| 233 |
} |
| 234 |
.greeting { |
| 235 |
font-size: 85%; |
| 236 |
} |
| 237 |
.motd { |
| 238 |
font-weight: bold; |
| 239 |
} |
| 240 |
</style> |
| 241 |
<h1>Guestbook</h1> |
| 242 |
<div><img class="banner" src="{{.BannerSrc}}"></div> |
| 243 |
{{with .MOTD}}<p class="motd">Admin says: {{.}}</p>{{end}} |
| 244 |
{{range .Greetings}} |
| 245 |
<div class="greeting"> |
| 246 |
Someone wrote: |
| 247 |
<blockquote>{{.Content}}</blockquote> |
| 248 |
</div> |
| 249 |
{{end}} |
| 250 |
<form action="/sign" method="POST"> |
| 251 |
<div><textarea name="content" rows="3"></textarea></div> |
| 252 |
<div><input type="submit" value="Sign"></div> |
| 253 |
</form> |
| 254 |
`)) |
| 255 |
|
| 256 |
// sign is a form action handler for adding a greeting. |
| 257 |
func (app *application) sign(w http.ResponseWriter, r *http.Request) { |
| 258 |
if r.Method != "POST" { |
| 259 |
w.Header().Set("Allow", "POST") |
| 260 |
http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed) |
| 261 |
return |
| 262 |
} |
| 263 |
content := r.FormValue("content") |
| 264 |
if content == "" { |
| 265 |
http.Error(w, "content must not be empty", http.StatusBadRequest) |
| 266 |
return |
| 267 |
} |
| 268 |
const sqlStmt = "INSERT INTO greetings (content) VALUES (?);" |
| 269 |
_, err := app.db.ExecContext(r.Context(), sqlStmt, content) |
| 270 |
if err != nil { |
| 271 |
log.Println("sign SQL error:", err) |
| 272 |
http.Error(w, "database error", http.StatusInternalServerError) |
| 273 |
return |
| 274 |
} |
| 275 |
http.Redirect(w, r, "/", http.StatusSeeOther) |
| 276 |
} |
| 277 |
|
| 278 |
// serveBlob handles a request for a static asset by retrieving it from a bucket. |
| 279 |
func (app *application) serveBlob(w http.ResponseWriter, r *http.Request) { |
| 280 |
key := mux.Vars(r)["key"] |
| 281 |
blobReader, err := app.bucket.NewReader(r.Context(), key, nil) |
| 282 |
if err != nil { |
| 283 |
log.Println("serve blob:", err) |
| 284 |
if gcerrors.Code(err) == gcerrors.NotFound { |
| 285 |
http.Error(w, "blob not found", http.StatusNotFound) |
| 286 |
} else { |
| 287 |
http.Error(w, "blob read error", http.StatusInternalServerError) |
| 288 |
} |
| 289 |
return |
| 290 |
} |
| 291 |
defer blobReader.Close() |
| 292 |
w.Header().Set("Content-Type", blobReader.ContentType()) |
| 293 |
w.Header().Set("Content-Length", strconv.FormatInt(blobReader.Size(), 10)) |
| 294 |
if _, err = io.Copy(w, blobReader); err != nil { |
| 295 |
log.Println("Copying blob:", err) |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
// appHealthChecks returns a health check for the database. This will signal |
| 300 |
// to Kubernetes or other orchestrators that the server should not receive |
| 301 |
// traffic until the server is able to connect to its database. |
| 302 |
func appHealthChecks(db *sql.DB) ([]health.Checker, func()) { |
| 303 |
dbCheck := sqlhealth.New(db) |
| 304 |
list := []health.Checker{dbCheck} |
| 305 |
return list, func() { |
| 306 |
dbCheck.Stop() |
| 307 |
} |
| 308 |
} |