MCPcopy Create free account
hub / github.com/GoogleCloudPlatform/golang-samples / saveVote

Function saveVote

cloudsql/postgres/database-sql/cloudsql.go:247–276  ·  view source on GitHub ↗

saveVote saves a vote passed as http.Request form data.

(w http.ResponseWriter, r *http.Request, db *sql.DB)

Source from the content-addressed store, hash-verified

245
246// saveVote saves a vote passed as http.Request form data.
247func 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
278var indexHTML = `
279<html lang="en">

Callers 1

VotesFunction · 0.70

Calls 1

ErrorMethod · 0.80

Tested by

no test coverage detected