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

Function saveVote

cloudsql/sqlserver/database-sql/cloudsql.go:235–264  ·  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

233
234// saveVote saves a vote passed as http.Request form data.
235func saveVote(w http.ResponseWriter, r *http.Request, db *sql.DB) {
236 if err := r.ParseForm(); err != nil {
237 log.Printf("saveVote: failed to parse form: %v", err)
238 http.Error(w, "Internal Server Error", http.StatusInternalServerError)
239 return
240 }
241
242 team := r.FormValue("team")
243 if team == "" {
244 log.Printf("saveVote: \"team\" property missing from form submission")
245 w.WriteHeader(http.StatusBadRequest)
246 return
247 }
248 if team != "TABS" && team != "SPACES" {
249 log.Printf("saveVote: \"team\" property should be \"TABS\" or \"SPACES\", was %q", team)
250 w.WriteHeader(http.StatusBadRequest)
251 return
252 }
253
254 // [START cloud_sql_sqlserver_databasesql_connection]
255 insertVote := "INSERT INTO votes (candidate, created_at) VALUES (@TEAM, GETDATE())"
256 _, err := db.Exec(insertVote, sql.Named("TEAM", team))
257 // [END cloud_sql_sqlserver_databasesql_connection]
258
259 if err != nil {
260 log.Printf("saveVote: unable to save vote: %v", err)
261 http.Error(w, "Internal Server Error", http.StatusInternalServerError)
262 }
263 fmt.Fprintf(w, "Vote successfully cast for %s!", team)
264}
265
266var indexHTML = `
267<html lang="en">

Callers 1

VotesFunction · 0.70

Calls 1

ErrorMethod · 0.80

Tested by

no test coverage detected