saveVote saves a vote passed as http.Request form data.
(w http.ResponseWriter, r *http.Request, db *sql.DB)
| 245 | |
| 246 | // saveVote saves a vote passed as http.Request form data. |
| 247 | func saveVote(w http.ResponseWriter, r *http.Request, db *sql.DB) { |
| 248 | if err := r.ParseForm(); err != nil { |
| 249 | log.Printf("saveVote: failed to parse form: %v", err) |
| 250 | http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 251 | return |
| 252 | } |
| 253 | |
| 254 | team := r.FormValue("team") |
| 255 | if team == "" { |
| 256 | log.Printf("saveVote: \"team\" property missing from form submission") |
| 257 | w.WriteHeader(http.StatusBadRequest) |
| 258 | return |
| 259 | } |
| 260 | if team != "TABS" && team != "SPACES" { |
| 261 | log.Printf("saveVote: \"team\" property should be \"TABS\" or \"SPACES\", was %q", team) |
| 262 | w.WriteHeader(http.StatusBadRequest) |
| 263 | return |
| 264 | } |
| 265 | |
| 266 | // [START cloud_sql_postgres_databasesql_connection] |
| 267 | insertVote := "INSERT INTO votes(candidate, created_at) VALUES($1, NOW())" |
| 268 | _, err := db.Exec(insertVote, team) |
| 269 | // [END cloud_sql_postgres_databasesql_connection] |
| 270 | |
| 271 | if err != nil { |
| 272 | log.Printf("saveVote: unable to save vote: %v", err) |
| 273 | http.Error(w, "Internal Server Error", http.StatusInternalServerError) |
| 274 | } |
| 275 | fmt.Fprintf(w, "Vote successfully cast for %s!", team) |
| 276 | } |
| 277 | |
| 278 | var indexHTML = ` |
| 279 | <html lang="en"> |