From 5b1d414ba23937e7fe1eba74547a7acf33e9c5a6 Mon Sep 17 00:00:00 2001 From: Joe Robinson Date: Mon, 21 Jul 2014 11:51:34 +0100 Subject: Added some error checking --- blavote.go | 59 +++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 16 deletions(-) (limited to 'blavote.go') diff --git a/blavote.go b/blavote.go index 9158e1c..857c904 100644 --- a/blavote.go +++ b/blavote.go @@ -8,12 +8,13 @@ import "os" import "io/ioutil" import "strings" import "strconv" +import "errors" var version string func main() { - version = "0.31" + version = "0.4" //Command line arguments var opts struct { @@ -75,7 +76,7 @@ func main() { fmt.Println(err) } } else if (opts.Remove > 0) { - deletePoll(db, opts.Remove, opts.Username) + err = deletePoll(db, opts.Remove, opts.Username) if (err == nil) { fmt.Print("Poll removed with ID ") @@ -85,11 +86,11 @@ func main() { } } else { - fmt.Println(opts.Args.Rest) vote(db, opts.Username, opts.Args.Rest) - } + } + } func connectDb(name string) (*sqlite3.Conn, error) { @@ -125,21 +126,47 @@ func initTables(db *sqlite3.Conn) { } -func vote(db *sqlite3.Conn, nick string, options []string) { +func vote(db *sqlite3.Conn, nick string, options []string) error { - if pollId, err := strconv.Atoi(options[0]); err == nil { - option := getOptionFromText(db, options[1]) - user := getUserForName(db, nick) - args := sqlite3.NamedArgs{"$a": user.id, "$b": pollId, "$c": option.id} - sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + pollId, err := strconv.Atoi(options[0]) - err := db.Exec(sql, args) + if (err != nil) { + return errors.New("Poll ID must be a number") + } - if (err != nil ) { - fmt.Print("Failed to vote: ") - fmt.Print(err) - } else { - fmt.Println("Vote added") + poll, err := getPollFromId(db, pollId) + + if (err != nil) { + return err + } + + option, err := getOptionFromText(db, options[1]) + + if (err != nil) { + return err + } + + user := getUserForName(db, nick) + + //Record the user in the DB if they aren't already + if (user.id == 0) { + user, err = createUser(db, nick, false) + + if (err != nil) { + return err } } + + args := sqlite3.NamedArgs{"$a": user.id, "$b": poll.id, "$c": option.id} + sql := "INSERT INTO votes (user_id, poll_id, option_id) VALUES ($a, $b, $c)" + + err = db.Exec(sql, args) + + if (err != nil ) { + fmt.Print("Failed to vote: ") + return err + } else { + fmt.Println("Vote added") + return nil + } } \ No newline at end of file -- cgit v1.2.3